9

I have seen too much C# and C++ code where the variable naming convention seems to ask programmers to write variable names using underscore before the text of the variable. e.gr.

int? _countMoney;

What's the rationale supporting that convention?

JPCF
  • 2,232
  • 5
  • 28
  • 50

10 Answers10

26

In C# I usually prefix with _ private fields but never local variables. The rationale behind this is that when I need a private variable I type _ and the Intellisense filters the list and it is easier to find. This way I am also able to distinguish between private from local variables and I no longer need to type this.variablename for class fields but simply _variablename.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I was doing this long before intellisense in order to distinguish member variables. It was a follow on from C++ days and MS using m_ for member variables – Peter M Sep 29 '10 at 18:20
  • 2
    If you can't determine whether or not a variable is local or not within a few seconds of looking at a method, could it not be argued that your method might be too complex? As for Intellisense filtering, is writing code tailored to a specific feature of an IDE really a good idea? – Justin Holzer Sep 29 '10 at 18:32
  • @Justin: While I agree with your first point, for your second point I have to ask if its really a bad idea? If it doesn't hurt readability, but occasionally helps writability, then why not use it? – Dennis Zickefoose Sep 29 '10 at 18:42
  • @Justin re:"is writing code tailored to a specific feature of an IDE really a good idea?" When the IDE in question is the de facto standard IDE for the language I think it is appropriate. It's not much different from using different coding conventions for different languages – Davy8 Sep 29 '10 at 18:45
  • @Davy8: In my opinion (which isn't worth much :) ), things like coding standards and naming conventions should be developed irrespective of any tool/framework/IDE. A variable naming convention should make just as much sense to be used in a basic text editor (i.e. Notepad) as it does in a big fancy IDE like Visual Studio or Eclipse. I'm not knocking Darin, or anyone else, for using a technique that helps them write better code. I'm just saying that I don't feel the Intellisense argument is a valid reason for using a particular naming convention. – Justin Holzer Sep 30 '10 at 12:46
  • 2
    @Justin On matter of principle I agree with you, but in practicality using VS for C# is pretty much an assumption unless stated otherwise. Certain things start making more sense when they become assumable (in a humanistic sense of 90%+ish and not a programming sense of 99.99%), like these days you can ask generally someone "what's your email address" without first asking whether they have one at all. 5-10 years ago you couldn't do that, and similarly for Java you can't assume Eclipse because other IDE's also have a fairly strong foothold. Python you can't assume anything about the editor. – Davy8 Sep 30 '10 at 13:07
  • Sorry went off on a bit of a tangent there, but was trying to make a (hopefully) cohesive analogy. – Davy8 Sep 30 '10 at 13:07
5

It's just an easy way to identify private member variables.

fehays
  • 3,147
  • 1
  • 24
  • 43
5

You should not use _ as a prefix in c++. Names starting with _ are reserved for the compiler.

The most common prefix is c++ is m_ (as in 'member)

For C# its very common to use _.

At my site where we do equal amount of c++ and c# we always use m_ to be consistent

Coding Mash
  • 3,338
  • 5
  • 24
  • 45
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 2
    No, in C++ names starting with _Uppercase are reserved. _lowercase are fine. – Detmar Sep 29 '10 at 17:04
  • 8
    @Detmar: Actually [it's more complicated than that](http://stackoverflow.com/questions/3650623/trailing-underscores-for-member-variables-in-c/3651336#3651336), but you both still have a point. – sbi Sep 29 '10 at 17:05
  • 1
    from standard "Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace". In theory you can get away with it, but why skate the edge? – pm100 Sep 29 '10 at 18:29
  • 2
    @pm100: "in the global namespace." Using it to indicate member fields is perfectly safe, not just safe in theory. Using it outside of a class is where where things get iffy, but that's foolish anywhow. – Dennis Zickefoose Sep 29 '10 at 18:47
  • 1
    The common way for local variables is now suffix with _ – mmmmmm Sep 29 '10 at 19:04
  • @Dennis: It's perfectly safe as long as oyu don't let that underscore follow by a capital letter. Oh, and then... two consecutive underscores are forbidden, too. If those rules were so easy, people wouldn't mess them up in answers. – sbi Oct 01 '10 at 21:32
5

The Microsoft Guidelines for member naming specifies that you do not use prefixes for fields.

Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields.

You can read Microsoft's guidelines for names here. This just applies to C#, of course.

SoManyGoblins
  • 5,605
  • 8
  • 45
  • 65
  • 1
    I personally dislike the practice of using a prefix. Your IDE should make it clear to you what's a local and what's a member. This is, of course, up to personal taste (or your project coding standards), but this answer gets my +1. – rmeador Sep 29 '10 at 17:33
  • This is one of the few guidelines which I happen to disagree with. I use `m_` and `s_` to distinguish between instance and static fields. This is important to me since you should assume that static fields could be accessed by multiple threads and as such you should take care to guard against threading issue. Using the prefixes in this manner makes it easy to see at a glance if there are any problem spots. This convention was proposed by Jeffery Richter who just happened to have a voice in developing this guideline. He must have lost on this particular point :) – Brian Gideon Sep 29 '10 at 18:09
  • 1
    @rmeador - IDE syntax coloring is not necessarily used in reading, nor does it copy to other environments [e.g., StackOverflow]. The prefix is in your face, and does copy to all environments. – Andy Thomas Sep 29 '10 at 18:37
  • 1
    Indeed, I do try to follow Microsoft guidelines when writing C# code, but my company uses prefixes to denote local variables (l), private member fields (m), static fields (s) and parameters (p). They are, as you say, right up in your face and you cannot not know what an identifier refers to. VS could probably do a better job at helping you distinguish the origin of identifiers, but sadly, it does not unless you do a mouse hover, which is not that helpful in large pieces of code with many identifiers. – SoManyGoblins Oct 01 '10 at 16:51
4

Like all other conventions it is about making code easier to understand.

I have seen this as a convention for private fields - in that case, it is very easy to see that a private field is being used.

You can ask the same question about hungarian notation.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 4
    Joel wrote an interesting defense of hungarian notation: http://www.joelonsoftware.com/articles/Wrong.html – Tim Yates Sep 29 '10 at 16:57
  • 3
    The key is using **Apps Hungarian** notation, not **Systems Hungarian**! – CaffGeek Sep 29 '10 at 17:51
  • While I'm not personally a fan of Hungarian notation, if it's being used to describe the value of a variable, I think it is far more acceptable. It's when people use it to denote something like a variable's type that I think it is misused. In Joel's article, he talks about using the "us" prefix to denote "unsafe strings". I would argue that in a modern language, like C#, if you want to use a prefix like that, the code would be more clear if you expanded the prefix "us" to "unsafe". – Justin Holzer Sep 29 '10 at 17:57
1

Like others have said, that naming convention helps distinguish member variables from locals. This gives two major advantages:

  • Helps pick out places where object state is being modified (important, for example, for thread safety)
  • Prevents naming clashes. I can write a constructor like:

    SomeObject(int foo, int bar)
    {
      _foo = foo;
      _bar = bar;
    }
    

    That way, I don't have to name the arguments new_foo or something like that.

Tim Yates
  • 5,151
  • 2
  • 29
  • 29
  • 2
    In C++ at least, you can write a constructor like this: `SomeObject(int foo, int bar) : foo(foo), bar(bar) {}`, and the "correct" thing occurs. – Oliver Charlesworth Sep 29 '10 at 16:59
  • True. This is something I learned in my C# days (where member initializer lists aren't allowed, IIRC). – Tim Yates Sep 29 '10 at 17:08
  • @sbi: Agreed. I do tend to do exactly this for PODs, though (assuming your definition of "POD" is allowed to encompass a constructor!) – Oliver Charlesworth Sep 29 '10 at 17:21
  • What would be so bad about dropping the underscore from your member variables and using the "this" keyword? – Justin Holzer Sep 29 '10 at 18:03
  • @Justin: To eliminate the possibility of mistakes? – Oliver Charlesworth Sep 29 '10 at 18:21
  • @Oli: What mistakes? If you're using Visual Studio, or most modern IDEs, the variable name can be automatically completed for you. – Justin Holzer Sep 29 '10 at 18:40
  • @Justin: The mistake of not typing `this` before you use the variable. – Dennis Zickefoose Sep 29 '10 at 18:49
  • @Justin: There are very few circumstances in which `foo = foo;` is not a mistake. – Dennis Zickefoose Sep 29 '10 at 20:18
  • @Dennis: There are countless numbers of mistakes that can be made like that, all of which are syntactically valid. Obviously, my opinions aren't shared by others in this thread, and that's fine. My real point is that I feel the most important thing to communicate in a variable name is the intent/purpose of the variable, and adding a prefix like "_" adds no value as far as communicating intent. Regardless of the scope that a variable is defined in, what good is it if you have no idea what it's being used for? – Justin Holzer Sep 30 '10 at 12:40
  • 1
    In this scenario, I personally would try to better describe "_foo" and "_bar" as something like currentFoo/currentBar or backingFoo/backingBar. In a lot of scenarios, prefixing with "current" describes something shared that is subject to change, and "backing" usually in the case it is something that can be accessed by a property. It really comes down to either company guidelines or personal preference depending on your situation, though. – Joseph Ferris Sep 30 '10 at 13:19
1

I'm not really sure what the rationale is behind this convention. Personally, I do not care for the use of any kind of variable name prefix for denoting the scope of a variable, nor do I particularly care for the use of underscores in naming anything. What's so bad about using the "this" keyword and adopting a convention of lower camel-cased names for private instance/member variables?

public void IncrementFoo()
{
    this.foo += 1;
}

It's only 5 additional characters to type, but it's very explicit. If you've adopted the lower camel-cased convention for your private instance variables, then this tells you right away that you're accessing a private instance/member variable, and you didn't need to use any kind of prefix to denote it.

Justin Holzer
  • 2,326
  • 2
  • 22
  • 22
0

Sometimes people do that in member variables to help distinguish them from local variables. If you're directly accessing an underscore variable, maybe you should be using a getter/setter for access instead.

Graham Perks
  • 23,007
  • 8
  • 61
  • 83
0

Something I noticed by Java devs in Eclipse when I had to do Java work, they wouldn't underscore there vars. Reason being? The members vars were color coded in the IDE...felt no need to do it so to speak. From habit it came naturally as I found it easy to locate a member var in the VS IDE by way of some visual cue...and underscore was it as it it fairly popular. In the rare event you have to look at code in its rawest form...text...those types of things help out tremendously.

Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
0

The _ prefix is pretty essential in VB.NET because it's not case-sensitive. We code in both C# and VB.NET, and for the sake of everyone's sanity it's important to have the same naming conventions in both languages.

Christian Hayter
  • 30,581
  • 6
  • 72
  • 99