To m_ or no to m_, that is the question…


I apologize for shocking your system by posting more than once a month – there are reasons for that, but I unfortunately can’t get into them right now – but Keith added an interesting comment to my last post. He said:


Side Note: a bit disturbing you’re using C++ naming conventions in C# though? πŸ™‚  No doubting your a ninja coder and I love your stuff, but seriously, bringing the m_ prefixing into C# is a bit of a “cant teach an old dog new tricks” thing.  


This is pretty close to a “religious question”, but since it’s my blog, I’m always right (as codified in the “decree on Gunnerson infallibility of 1997”), so I’ll take it on.


When I first started writing code, a lot of our samples were written without any way of indicating whether something was a field or not, and I wrote a considerable amount of code using that idiom. What I found was that when I went back and looked at my code later, I had to scroll around to find out where each variable came from, and that made understanding the code harder.


I toyed for a while with using just and underscore “_name”, but I didn’t like that. A single underline is a bit hard to pick up visually, and it seemed like I was inventing a different expression just to be different. So, I switched back to “m_”, and I must say that I’m happy with the choice. The only place I don’t like it is with events or other public fields, which are then named differently, but I’m willing to deal with that.


The only other place I use prefixes is on pointers, where I just use “p”. Unsafe code is rare enough that I want to have an indicator of what’s going on.


[Update: Another reason to use m_ is to make it easier to find your variable names in intellisense when you’re working with controls, since there are roughly 4000 members in the average control class. I’ve also been using “c_” in the names of controls for the same reason]


So, what do you think, keeping in mind that if you disagree, you’re wrong…

Comments (44)

  1. Thomas says:

    I’ve never personally understood the prefix rationale in C++ and C# as far as "where did it come from" go.. Just use "this->" or "this." respectively if you can’t deal without.

    Personally, I use _foo for private stuff in python (that’s the python convention), fooBar in C# (like all vars), and foo_ in C++ (_foo is reserved, and foo_ is the boost convention for private members).

  2. Mike Dunn says:

    I’ve never understood why some people refuse to write "m_" (a 2-character prefix) but are just fine with writing "this." (a FIVE-character prefix).

  3. MSDNArchive says:

    I’m torn between using _foo and using foo, though I’m tending toward the latter lately.

    As regards ‘this’, I use it because it carries semantic meaning that the language dictates, rather than meaning that is lost when you cross the hallway.

    I’d be interested in seeing what a language would look like if it had a specific notation for private fields or local variables, which didn’t conflict with public members.  Then this argument would be moot. πŸ™‚

  4. Thomas says:

    Mike Dunn – Because m_ is in the variable name, this. or this-> is in the language and carries semantic meaning, like kfarmer mentions.

    Furthermore it allows you to omit it where it’s clear without clarifying scope of the var.

    Personally, I like python convention with ‘self’ and ‘_foo’.

  5. Tom says:

    I’ve written a lot of C# code, and I really don’t understand the need to distinguish between member private fields, local variables, and parameters/arguments.  I don’t think it matters most of the time where the variable is declared, as long as it is known to be in scope, has a known meaning and type, etc.  I like them all use the same naming convention — it makes the code cleaner and makes it easy to move the definition of a variable between any of these three locations without refactoring.

    I specifically dislike prefixes like "m_" and "_" because they slow down typing and IntelliSense matching.  They also look ugly and make the code look more cryptic when reading it later when maintaining the code.

  6. Tyler Jensen says:

    I go back and forth. Some days are "m_" days and others are not. I think it relates to how much database work I’m doing that day and whether I’m use to typeing the underscore. But at the end of the day, if I can read it and I can reasonably conclude that others can read it and it compiles, I’m good.

  7. Ramon Leon says:

    Personally, I think _ is an abomination that doesn’t belong in code, so I prefix member variables with "the".  It reads well, allows me to speak about the code out loud without sounding like an idiot.  I prefix arguments with a/an, and local variables have no prefix.  "this." is just a bit too much to type.

  8. Thomas Eyde says:

    You don’t happen to suffer from long methods and/or long classes, do you?

  9. yuriy says:

    Using the same m_ and c_ and like this approach.

  10. Peter Ritchie says:

    In C++ there is a rational for a prefix like (like "m_").  In the initializer list you cannot use "this" for scope resolution.  So, to avoid having parameter name collisions with fields "m_" is used to delineate fields.

    C# was designed to not need the prefix.

  11. Peter Ritchie says:

    @bleroy: Brad reserves the right to be inconsistent, consistently πŸ™‚

  12. Thomas says:

    Peter – Except, there’s no collision: Foo(int bar, int x) : bar(bar) { this->x = x; } works perfectly fine.

  13. John says:

    There is a good reason to use _, or something in front of your member variables. CLS compliance.  Remember that that not all CLS languages are case-sensitive ( I won’t mention any names), so member variable foo and property Foo would cause problems in other languages.

  14. Peter Ritchie says:

    RE: CLS compliance.  Only if the fields are public; which is a no-no…

  15. Peter Ritchie says:

    Thomas – not all compilers agree.  Even still bar(bar) is horrible for readability.

  16. Thomas says:

    Peter – Sure, it’s not the most readable, but for an init list I honestly don’t care; There’s no ambiguity present.

    As for compilers, I’ve used it with MSVC/GCC/Intel without issue for many years.

  17. I use _ rather than m_…it’s one character less but I’m not really bothered with one or the other. Having said that as far as I’m concerned I must have a field prefixer, it’s easier to see what’s going on in the code; you can’t rely on ‘this.’ as some fields are static. Also it stops mistakes where some locals can have the same name as a field and you don’t realise it.

    Regards

    Lee

  18. MSDNArchive says:

    The ‘_’ prefix has the advantage that intellisense lists all your private fields at before all other members, at the top of the list.

    I’m the only person I’ve met who likes to use both the ‘_’ prefix *and* the ‘this.’ qualifier on field references.  

    This is because, after working on C# IntelliSense for a few years, I am very comfortable using its features.  ‘this._’ is a powerful way of directing IntelliSense to get you what you want.

  19. Peter Ritchie says:

    Sorting in the class/member/intellisense list has to be the worst reason for prefixes.  

  20. Peter Ritchie says:

    Just use "ClassName." on static members…

  21. I totally agree with you Peter.

    I can understand the use of β€œ_” to distinguish scope (if you need it, you need it).

    What I can’t understand is the β€œm_”. What does β€œm_” stand for? (I already wrote about this, so I’m not going over that again – http://msmvps.com/blogs/paulomorgado/archive/2007/05/20/naming-conventions-for-c.aspx

    I’m forced to use β€œm_” at work but I always qualify instance fields with β€œthis.” and static fields with the type name. I’ve reviewed code where a developer changed the use of something from a class field to a local variable (keeping the β€œm_” prefixed name because it just started as a test) and was not understanding  why the field was having its valued changed just inside that method. When I started qualifying all fields the bug surfaced immediately.

  22. Steven says:

    jaybaz_MS,

    You’re not alone in this world ;-). I both use _ prefix for private member variables and the this. qualifier on references to those fields.

    I think the _ prefix is the shortest most readable prefix for private fields that share the same name as the properties they most of the time belong too and ‘this.’ makes my code more readable by separating local from member variables.

  23. Peter Ritchie says:

    Agreed Paulo (your comment and your blog entry).  I think Hungarian Notation and prefixes just lead to lazy programmers and poor identifier naming.

    If we named our members "asdf" or "i" or other equally obtuse member names then I could see the need to prefix it; because you can’t possibly know what the identifier is for.

    With proper design, programming and naming of identifiers there’s no need for "m_" or Hungarian notation.

    If the code is so complex as to require the addition "m_" to identifier names, you’ve probably got other problems (possibly poor choice for identifier names, lack of cohesion, high coupling, violation of Single Responsibility Principle, etc. [1])

    No one has shown me an example of code that once redesigned to properly adhere to generally accepted design/programming principles and meaningful naming guidelines could benefit from from prefixes, even outside of an IDE.

    Eric’s GetIdentifiers example: nowhere in that class could "identifiers" be confused as being anything other than a member of the class other than WriteToConsole() where a simple "this.identifiers.keys" would have sufficed.  The argument that "m_" is less typing that "this." falls short here because 4 "m_"’s is more typing that one "this.".  "Well, GetIdentifiers is just a simple class" just further proves arbitrary prefixing is knee-jerk and habitual–which I’m fine with, just admit to it.

    I’m even not a big fan of the "I" prefix, I only accept it because it’s so pervasive.

    [1] http://blogs.msdn.com/ericlippert/archive/2007/06/12/bad-names.aspx

  24. The periodic identifier naming/prefixing/Hungarian-notation religions discussion reared its head recently

  25. Binaryjam says:

    I was in a meeting to help set our company standard for naming in C# and we went with the path of leasast resistance for FxCop.  However for private variables what to do.  So many different ideas.

    In the end we plumbed for no underscores or prefixes just lower case start.

    What a mistake.

    I wish I had shouted for m_ or c_ its just so much easier to find things in intellisense.  You get variable name grouping and you can type the code so much faster then.

    Thats what mattered to me. Then in reading it later it was easy to see in the code without having to step through every line thats a var thats a control.  I admint I don’t want to go down to type identification as well just a quick ref to scope is enough. Now we are inte preference I suppose.

    Whatever you do you can’t win someone will hate what you do as its all down to preference in the end and what you were brought up on.

    Perhaps we could start them with  WS01-  for working storgage ?

  26. this.variable <– class scope variable

    ClassName.variable <– class scope static variable

    variable <– local scope variable

    Your methods should never be longer than a few lines, so examining whether "variable" is a parameter to the method or one you declared locally should not be a problem.

    Using "this." and "ClassName" makes the scope of the variable explicit and EVERY developer out there that knows what these mean (do you want them working for you if they don’t?) can understand the coding standard without having to read a document.

    What is even more important is that this can also be applied to methods consistently.

    this.MethodName() <– class scope method

    ClassName.MethodName() <– static scope method

  27. James Sugrue says:

    I used to use "m_", but after I started using FxCop I reverted to using "_" to prefix private variables.

    I don’t like using camel casing for private vars and Pascal casing for public fields because it’s too easy to transpose.

    Eg:

    private int myInt;

    public int MyInt…

    it’s too easy to put MyInt in the wrong place. _myInt is much harder to stuff up. Plus, IMO it makes it easier to spot private vars when scanning code.

  28. Gavin Greig says:

    We use "my" for this. It’s the same length as "m_", it’s a real word, and it expresses the ownership relationship between the class and the member variable.

    We didn’t want to use Hungarian when we moved to C# but we came to the conclusion that there’s a difference between including type information (not a good idea any more) and what could be described as variable meta-information – like it how it is meant to be stored or used.

    For us, indicating whether a variable is a member variable fell into the realm of useful meta-information.

    We wound up picking a short list of approved lower-case prefixes for variables. Our aims were to give some useful meta-information, to comply with the camel-case recommendation of the Framework Design Guidelines and FxCop, and to use meaningful words to do it. Oh, and just in case it wasn’t clearly implied by that last point, we wanted to completely eliminate underscores! At least one member of the team went into convulsions at the very sight of an underscore πŸ˜‰

    Here’s our list of prefixes:

    const: a constant

    my: a member variable of a class

    a (or an): a local variable used to access members of a collection

    loop: a local variable that will be used to control a loop

    the: any other local variable

    in: a parameter that is only passed in to the method

    out: a parameter that will hold data inserted by the method

    io: a parameter that performs both "in" and "out" roles

    In practice, I’m not sure if we’ve ever used "out" or "io", but the others are used consistently in our code and do seem to prove useful.

  29. chrisb says:

    Even though I’m obviously wrong, my vote goes to this.Public and _Private

  30. class Foo

    {

      private int bar;

      public int Bar { … }

    }

    1.  As I’ve said before, basing naming decisions on the amount of typing you’ll have to do is ALWAYS wrong.  Intellisense and code snippets, if required, can always reduce typing to at least as little as you could reduce the name to, sometimes to even less.

    2.  Basing a naming convention on the need to know where a variable is declared is just as wrong.

    2a.  Usage should usually make it obvious.

    2b.  When it’s not obvious, you’ve got an indication of a much bigger code smell that needs corrected now.  The most likely problem is that you have a function that’s too long and needs refactored.  Effort spent doing this will pay off much more than any effort made in using prefixes to distinguish where a variable is declared.

    3.  When there’s a collision between a local and a member, "this." and "Class." are more meaningful ways to distinguish.  I prefer to reserve this for when there are collisions, but if you’re in the "less typing/use intellisense" crowd, I have no problems with using this more liberally (by the way, a code snippet for "this." can reduce typing to 2 characters, the same as your "m_" prefix, but with the added benefit of calling up intellisense).

    4.  CLS compliance should never be an issue here.  Public/Protected fields and properties are always Pascal.  Private fields are always Camel.  No combination of properties and fields should result in a collision or CLS compliance issue.

    5.  Code reads better with out prefixes.

  31. Steve Dunn says:

    m_ in hungariant mean ‘member’, which was needed to separate from globals ‘g_’.  Since globals are a thing of the past in C#, so should ‘m_’.  Typing in ‘underscore+ctrl+space’ to get intellisense to list my members is extremely handy!

    One of thing that I tend to do (and which I wish others would do), is to camelCase private methods (as opposed to PascalCased PublicMethods).  This helps you see straight away which members and public or private.

    Of course, I disagreed with Eric’s m_ argument which makes me wrong – but I redeemed myself by being correct on camelCasing privates. πŸ™‚

  32. David Hayes says:

    I like to use mMyVariableName, _ is no good because then your classes aren’t CLS compliant if you use a protected variable. m_ is too much to type IMO.

  33. Ade Miller says:

    I’m OK with ‘_’ or "m_"…

    See: In praise of ‘_’

    http://ademiller.spaces.live.com/blog/cns!769B86D17666DFEF!237.entry

  34. Bobby Cannon says:

    I use the ‘_variable’ for all Global variables and just ‘variable’ when in methods. The ‘_’ allows me to quickly see if the variable is global!

  35. Foi lançada um discução no blog do Eric Gunnerson acerca do assunto "Prefixar com m_ ou não prefixar

  36. David Conrad says:

    Actually, the IDE should show public, private, and local variables in separate fonts. Const or static identifiers would be distinctive as well, and globals, in languages that have them, would be displayed using the blink tag.

  37. Sure are a lot of people who have comments without any intelligence behind there statements. Personal preference for your own being don’t count. What works will with programs and others that need to review / examine your writings is the only thing that matters.

  38. How many naming conventions were violated here?

    http://msdn2.microsoft.com/1h3cat6t.aspx

  39. I hate underscores, since they’re actually one character for the cost of *2* keystrokes. So I use just an "m": mVariableName.

    As was suggested above, I use "c" for constants. Add to this, for static fields, an "s".

  40. Peter Ritchie says:

    I like Joseph Newcomer’s comments on the topic of "m_".

    He describes the use of "m_" merely as a compulsion.

    And "…if using "m_" was the only correct and sensible way to designate member variables, don’t you think Bjarne Stroustrup would have designed the language that way and no other?"

  41. Nuno Godinho says:

    I fully agree with Paulo and Peter because the prefix normally shows that the code is not really readable enough, and so the prefix appears to save the day.

    I normally use in private fields the name using camelCasing, and when i call it normally i use  because this.<fieldname>.

    As for the m_ or _, i normally don’t use none of them, but the _ doesn’t shock me because it has the nice this of putting all that fields first in the intellicense, but i don’t like the m_, because i don’t know why m_ and and not v_, i_ or anything else in the alphabet. If this m_ is really the a naming convension then i agree with Paulo, the next stop will be Hungarian notation again, and honestly i hate it.

  42. Nuno Godinho says:

    I fully agree with Paulo and Peter because the prefix normally shows that the code is not really readable enough, and so the prefix appears to save the day.

    I normally use in private fields the name using camelCasing, and when i call it normally i use this.<fieldname>.

    As for the m_ or _, i normally don’t use none of them, but the _ doesn’t shock me because it has the nice this of putting all that fields first in the intellicense, but i don’t like the m_, because i don’t know why m_ and and not v_, i_ or anything else in the alphabet. If this m_ is really the a naming convension then i agree with Paulo, the next stop will be Hungarian notation again, and honestly i hate it.

  43. TValoy says:

    When we started using C# at work we first tried without prefix. This caused hard to spot errors in our code when the parameter name was spelled the same as the field name (especially when setting a property value in a constructor).

    We considered the use of this., but found that the problem was that the compiler does not enforce consistent usage. If the field has a prefix, then the compiler forces you to use it.

    To ensure consistency we implemented an fxcop-rule to enforce the m_ prefix.

    Trygve