views:

817

answers:

18

It's usually to see a _var variable name in a class field. What does the underscore mean? Is there a reference for all these special naming convention? Thanks.

+1  A: 

No, it depends on your team.

for example:

  • Google chromium os project uses var_ at the end.

  • In our team, we use m_var, s_var, for member and static respectively.

Gollum
A: 

It's simply means that it's a member field in the class.

hkon
A: 

There's no particular single naming convention, but I've seen that for private members.

Cade Roux
+1  A: 

The Microsoft naming standard for C# says variables and parameters should use the lower camel case form IE: paramName. The standard also calls for fields to follow the same form but this can lead to unclear code so many teams call for an underscore prefix to improve clarity IE: _fieldName.

ChaosPandion
Can someone leave a comment so I can improve my answer?
ChaosPandion
Then I got an extra question. What if the parameter name and local variable name are the same. How do people usually name them? ie. void MyClass(int count) { int count2; return;} thanks.
Stan
@Stan - I always try and write my code to avoid situations like that but typically I will name the variable with a description of what occurred IE: `var trimmedValue = (value ?? string.Empty).Trim();`. So far this has worked out great.
ChaosPandion
camelCaseMakesMeWantToBarf
Inverse
+6  A: 

The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:

In C++, an underscore usually indicates a private member variable.

In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.

Before:

private string _name;
public string Name
{
    get { return this._name; }
    set { this._name = value; }
}

After:

public string Name { get; set; }
jdmichal
Except for teams that want their properties to be immutable.
ChaosPandion
Identifiers starting with underscores are reserved for the compiler. Using prefix underscores **may** conflict with compiler symbols.
Thomas Matthews
@Thomas Matthews - not in C#.
Evgeny
@ChaosPandion I'm assuming that what you mean by "immutable" is actually "read-only", in which case one can use `public string Name { get; private set; }`. True, it's not perfectly immutable, but it's there.
jdmichal
@Thomas In a class context, identifiers starting with underscores *followed by a capital letter* a reserved in C++. `_var` is not reserved.
Tyler McHenry
A: 

From my experience (certainly limited), and underscore will indicate that it is a private member variable. As Gollum said, this will depend on the team, though.

Smashery
A: 

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

Daedylus
A: 

Many people like to have private fields prefixed with an underscore. It is just a naming convention.

C#'s 'official' naming conventions prescribe simple lowercase names (no underscore) for private fields.

I'm not aware of standard conventions for C++, although underscores are very widely used.

Mau
A: 

A naming convention like this is useful when you are reading code, particularly code that is not your own. A strong naming convention helps indicate where a particular member is defined, what kind of member it is, etc. Most development teams adopt a simple naming convention, and simply prefix member fields with an underscore (_fieldName). In the past, I have used the following naming convention for C# (which is based on Microsofts conventions for the .NET framework code, which can be seen with Reflector):

Instance Field: m_fieldName
Static Field: s_fieldName
Public/Protected/Internal Member: PascalCasedName()
Private Member: camelCasedName()

This helps people understand the structure, use, accessibility and location of members when reading unfamiliar code very rapidly.

jrista
Actually, Microsoft don't recommend to use m_, s_ prefixes.*Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields.* http://msdn.microsoft.com/en-us/library/ms229012.aspx
Zied
Like I said, take a look at their source code with Reflector. You'll be surprised how much they shirk their own recommendations. ;) As my post mentioned, it helps improve the readability of your code, and my last team really liked the naming convention listed above.
jrista
A: 

It's just a convention some programmers use to make it clear when you're manipulating a member of the class or some other kind of variable (parameters, local to the function, etc). Another convention that's also in wide use for member variables is prefixing the name with 'm_'.

Anyway, these are only conventions and you will not find a single source for all of them. They're a matter of style and each programming team, project or company has their own (or even don't have any).

goedson
A: 

With C#, Microsoft Framework Design Guidelines suggest not using the underscore character for public members. For private members, underscores are OK to use. In fact, Jeffrey Richter (often cited in the guidelines) uses an m_ for instance and a "s_" for private static memberss.

Personally, I use just _ to mark my private members. "m_" and "s_" verge on Hungarian notation which is not only frowned upon in .NET, but can be quite verbose and I find classes with many members difficult to do a quick eye scan alphabetically (imagine 10 variables all starting with m_).

P.Brian.Mackey
+3  A: 

Actually the _var convention comes from VB not C# or C++ (m_,... is another thing).

This came to overcome the case insensitivity of VB when declaring Proprieties

for example such code isn't possible in VB because it consider user and User as the same identifier

Private user As String

Public Property User As String
  Get
    Return user
  End Get
  Set(ByVal Value As String)
    user = value
  End Set
End Property

So to overcome this, some used a convention to add '_' to the private field to come like this

Private _user As String

Public Property User As String
  Get
    Return _user
  End Get
  Set(ByVal Value As String)
    _user = value
  End Set
End Property

Since many convention are for .Net and to keep some uniformity between C# et VB.NET convention, they are using the same one.

I found the reference for what I was saying : http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices

Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that differs from the property by only case, especially with protected variables as that violates compliance, and will make your life a pain if you program in VB.NET, as you would have to name your members something different from the accessor/mutator properties. Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore. As far as m_ goes, it is really just about aesthetics. I (and many others) find m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive. I used to use it in VB6 all the time, but that was only because variables could not have a leading underscore. I couldn't be happier to see it go away. Microsoft recommends against the m_ (and the straight _) even though they did both in their code. Also, prefixing with a straight "m" is right out. Of course, since they code mainly in C#, they can have private members that differ only in case from the properties. VB folks have to do something else. Rather than try and come up with language-by-language special cases, I recommend the leading underscore for all languages that will support it. If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables. In practice, however, I never worry about this as I keep all potentially protected member variables private, and supply protected accessors and mutators instead. Why: In a nutshell, this convention is simple (one character), easy to read (your eye is not distracted by other leading characters), and successfully avoids naming collisions with procedure-level variables and class-level properties.class-level properties.

Zied
+1  A: 

You can create your own coding guidelines. Just write a clear documentation for the rest of the team.

Using _field helps the Intelilsense to filter all class variables just typing _.

I usually follow the Brad Adams Guidelines, but it recommends to not use underscore.

Tony Alexander Hild
+3  A: 

The first commenter (R Samuel Klatchko) referenced: What are the rules about using an underscore in a C++ identifier? which answers the question about the underscore in C++. In general, you are not supposed to use a leading underscore, as it is reserved for the implementer of your compiler. The code you are seeing with _var is probably either legacy code, or code written by someone that grew up using the old naming system which didn't frown on leading underscores.

As other answers state, it used to be used in C++ to identify class member variables. However, it has no special meaning as far as decorators or syntax goes. So if you want to use it, it will compile.

I'll leave the C# discussion to others.

bsruth
A: 

There is a fully legit reason to use it in C#: if the code must be extensible from VB.NET as well. (Otherwise, I would not.)

Since VB.NET is is case insensitive, there is no simple way to access the protected field member in this code:

public class CSharpClass
{
    protected int field;
    public int Field { get { return field; } }
}

E.g. this will access the property getter, not the field:

Public Class VBClass
    Inherits CSharpClass

    Function Test() As Integer
        Return Field
    End Function

End Class

Heck, I cannot even write field in lowercase - VS 2010 just keeps correcting it.

In order to make it easily accessible to derived classes in VB.NET, one has to come up with another naming convention. Prefixing an underscore is probably the least intrusive and most "historically accepted" of them.

andras
+1  A: 

As far as the C and C++ languages are concerned there is no special meaning to an underscore in the name (beginning, middle or end). It's just a valid variable name character. The "conventions" come from coding practices within a coding community.

As already indicated by various examples above, _ in the beginning may mean private or protected members of a class in C++.

Let me just give some history that may be fun trivia. In UNIX if you have a core C library function and a kernel back-end where you want to expose the kernel function to user space as well the _ is stuck in front of the function stub that calls the kernel function directly without doing anything else. The most famous and familiar example of this is exit() vs _exit() under BSD and SysV type kernels: There, exit() does user-space stuff before calling the kernel's exit service, whereas _exit just maps to the kernel's exit service.

So _ was used for "local" stuff in this case local being machine-local. Typically _functions() were not portable. In that you should not expect same behaviour across various platforms.

Now as for _ in variable names, such as

int _foo;

Well psychologically, an _ is an odd thing to have to type in the beginning. So if you want to create a variable name that would have a lesser chance of a clash with something else, ESPECIALLY when dealing with pre-processor substitutions you want consider uses of _.

My basic advice would be to always follow the convention of your coding community, so that you can collaborate more effectively.

Elf King
A: 

Now the notation using "this" as in this.foobarbaz is acceptable for C# class member variables. It replaces the old "m_" or just "__" notation. It does make the code more readable because there is no doubt what is being reference.

ddm
+1  A: 

_var has no meaning and only serves the purpose of making it easier to distinguish that the variable is a private member variable.

In C++, using the _var convention is bad form, because there are rules governing the use of the underscore in front of an identifier. _var is reserved as a global identifier, while _Var (underscore + capital letter) is reserved anytime. This is why in C++, you'll see people using the var_ convention instead.

5ound