Naming convention - underscore in C++ and C# variables

C#C++Naming Conventions

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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; }

Solution 2 - C#

It is best practice to NOT use UNDERSCORES before any variable name or parameter name in C++

Names beginning with an underscore or a double underscore are RESERVED for the C++ implementers. Names with an underscore are reserved for the library to work.

If you have a read at the C++ Coding Standard, you will see that in the very first page it says:

> "Don't overlegislate naming, but do use a consistent naming convention: There are only two must-dos: a) never use "underhanded names," ones that begin with an underscore or that contain a double underscore;" (p2 , C++ Coding Standards, Herb Sutter and Andrei Alexandrescu)

More specifically, the ISO working draft states the actual rules:

> In addition, some identifiers are reserved for use by C ++ implementations and shall not be used otherwise; no diagnostic is required. (a) Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use. (b) Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

It is best practice to avoid starting a symbol with an underscore in case you accidentally wander into one of the above limitations.

You can see it for yourself why such use of underscores can be disastrous when developing a software:

Try compiling a simple helloWorld.cpp program like this:

g++ -E helloWorld.cpp

You will see all that happens in the background. Here is a snippet:

   ios_base::iostate __err = ios_base::iostate(ios_base::goodbit);
   try
     {
       __streambuf_type* __sb = this->rdbuf();
       if (__sb)
  {
    if (__sb->pubsync() == -1)
      __err |= ios_base::badbit;
    else
      __ret = 0;
  }

You can see how many names begin with double underscore!

Also if you look at virtual member functions, you will see that *_vptr is the pointer generated for the virtual table which automatically gets created when you use one or more virtual member functions in your class! But that's another story...

If you use underscores you might get into conflict issues and you WILL HAVE NO IDEA what's causing it, until it's too late.

Solution 3 - C#

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 Properties.

For example, such code isn't possible in VB because it considers 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 conventions 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.

Solution 4 - C#

_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.

Solution 5 - C#

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.

Solution 6 - C#

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.

Solution 7 - C#

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_).

Solution 8 - C#

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.

Solution 9 - C#

Old question, new answer (C#).

Another use of underscores for C# is with ASP NET Core's DI (dependency injection). Private readonly variables of a class which got assigned to the injected interface during construction should start with an underscore. I guess it's a debate whether to use underscore for every private member of a class (although Microsoft itself follows it) but this one is certain.

private readonly ILogger<MyDependency> _logger;

public MyDependency(ILogger<MyDependency> logger)
{
    _logger = logger;
}

EDIT:

Microsoft adopted use of underscores for all private members of a class for a while now.

Solution 10 - C#

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.

Solution 11 - C#

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.

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

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.

Solution 16 - C#

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).

Solution 17 - C#

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.

Solution 18 - C#

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.

Solution 19 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStanView Question on Stackoverflow
Solution 1 - C#jdmichalView Answer on Stackoverflow
Solution 2 - C#Constantinos GlynosView Answer on Stackoverflow
Solution 3 - C#ZiedView Answer on Stackoverflow
Solution 4 - C#5oundView Answer on Stackoverflow
Solution 5 - C#bsruthView Answer on Stackoverflow
Solution 6 - C#Tony Alexander HildView Answer on Stackoverflow
Solution 7 - C#P.Brian.MackeyView Answer on Stackoverflow
Solution 8 - C#ChaosPandionView Answer on Stackoverflow
Solution 9 - C#Baz GuvenkayaView Answer on Stackoverflow
Solution 10 - C#A.J.View Answer on Stackoverflow
Solution 11 - C#Elf KingView Answer on Stackoverflow
Solution 12 - C#hkonView Answer on Stackoverflow
Solution 13 - C#Cade RouxView Answer on Stackoverflow
Solution 14 - C#SmasheryView Answer on Stackoverflow
Solution 15 - C#MauView Answer on Stackoverflow
Solution 16 - C#goedsonView Answer on Stackoverflow
Solution 17 - C#Andras VassView Answer on Stackoverflow
Solution 18 - C#ddmView Answer on Stackoverflow
Solution 19 - C#jristaView Answer on Stackoverflow