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

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?

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

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.

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.

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

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.

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.

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

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.

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.

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.

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.

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.

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

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

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.

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

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.

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.

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.

Related

Long (readable) names in Generics/Templates

I find myself sometimes writing code that looks like this with Java Generics:
/**Class description
*#param <K> Key to '.....'
public class Mappy<K>{
///class methods, fields, etc....
}
Sometimes using single-character names has caused slowdowns when months later I return to code and have to keep scrolling up to remember what "T" & "E" are. But last I checked, Oracle's official guideline was single-character names and I've never seen a java programmer not do it.
In C#, using TDescription is part of the official style guidelines, similar to how Google & others use Ixxxx for interfaces. But I still see one-letter names in production code & APIs for C#. I've heard it is similar in C++. In Haskell & Ocaml, especially Haskell, you use 'a' or 'b' as a generic parameter in your function signature (forget if the compiler/interpreter forces this or if they can be multi-letter).
I'm just asking this 'question' to see how y'all do it: do you stick with single-letter names in your generics/templates/etc..., do you have a convention like Txxx, do you give them full-fledged names (and does that confuse co-workers), or do you do something else?
This is very similar to Breaking java generics naming convention? (which I found via google). Instead of poking that question, I just wanted to gather some modern opinions (see if there's been a style coup in the pass two and a half years).
Edit 1:
Probably the reason this question came up is that a few days ago I made a pledge to dump the variable 'i'. Too many times using the quick & dirty loop variable 'i' has caused issues in nested loops & refactoring so I decided to go with only full-fledged names.
Naming conventions exist as a tool to help you maintain readable code.
They are there to help you. They are not a rule.
There's a higher value to have easy to read - maintainable code than to blindly follow a naming convention.
I use single-letter uppercase types in my generics when the type can be (almost) any type. Like with Map<K,V> etc.
However, when the type has more meaning than just ANY type, such as:
public class Table<Column extends Enum<Column> & Table.Columns> {
...
public interface Columns {
...
I use a more appropriate name Column but retain the convention of the initial uppercase. I feel it is important to maintain brevity for types as you are likely to use it many times in the code. A single uppercase character is - you must admit - perfect brevity.

Naming conventions for private members of .NET types [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Normally when I have a private field inside a class or a struct, I use camelCasing, so it would be obvious that it's indeed private when you see the name of it, but in some of my colleagues' C# code, I see that they use m_ mostly or sometimes _, like there is some sort of convention.
Aren't .NET naming conventions prevent you from using underscores for member names?
And when you mention the MS naming conventions or what not, they tell you theirs is the best way, but don't explain the reasoning behind it.
Also when I am the owner of some code, where I clearly use camelCasing for private members, when they have to make a minor modification to the code, they stick in their conventions instead of following whatever conventions are there.
Is this a controversy?
The .Net framework guidelines allow for a _ or m_ prefix on private field names because the provide no guidance on private fields. If you look at the BCL in reflector you'll notice a prefix is the most prevalent pattern.
The Reference page for naming fields is located here. Notice the guidelines only specify usage for public and protected fields. Private fields are simply not covered.
Technically, underscores are a violation of .NET conventions (or at least used to be -- see comment thread), but Microsoft programmers themselves often use underscores, and many examples in the documentation use underscores. I think it's very helpful to be able to see at a glance which variables are member variables (fields) and which are local. The underscore really helps with this. It also nicely separates private member variables from local variables in intellisense.
Please see this very useful page for .NET naming conventions:
http://10rem.net/articles/net-naming-conventions-and-programming-standards---best-practices
And here's a page with Microsoft's official recommendations:
https://msdn.microsoft.com/en-us/library/ms229045%28v=vs.110%29.aspx
I typically prefix private member variables with an underscore.
It just makes them easier to spot when you're trying to read the code and it's allowed by the Microsoft Guidelines:
public class Something
{
private string _someString = "";
public string SomeString
{
get
{
return _someString;
}
set
{
// Some validation
_someString = value;
}
}
}
Like others have said, the more important thing is to be consistent. If you're on a team that has a coding standard that does things the m_ way, don't try to be a rebel and do yours another. It will just make things more difficult for everybody else.
well, microsoft is not taking part for any of the 2 options.
If on Visual Studio you encapsulate a field using "refactor->Encapsulate Field..." for
private string _myVar
and
private string myVar
both of them generates a propery like this
public string MyVar
{
get { return myVar; }
set { myVar = value; }
}
So for microsoft it's the same :-) It's only a question of reaching an agreement with the development team so everyone uses the same approach.
Normally I never use private fields except very specific situations. I encapsulate private fields with protected properties. Better for inheritance and more clear IMHO.
Even in the BCL you see a lot of inconsistency with naming conventions, some classes have "_", some "m_" and some just the pascal case version of the property.
Underscore is good because you prevent accidental stackoverflows, although more recent versions of Visual Studio warn you about this anyway. They also appear first in your intellisense, avoiding the need to riddle your code with this.someProperty or search through the entire list.
As long as the team agrees on one standard it doesn't make a whole lot of difference, but having used underscores for 5+ years I personally wouldn't want to return back to the alternatives.
If you own the codebase and maintain it, I would insist they use your standards. If they don't then simple refactor it combined with a polite email why you've done it.
There are two MSDN articles (here and here) about design guidelines that also contain naming conventions. Too bad they are restricted to "publically visible" things. They don't offer guidelines for naming non-public things and as far as I know Microsoft doesn't provide official naming guidelines for non-publics.
StyleCop (a Microsoft tool) is against using underscores in names. Two reasons I have heard from developers why they prefer to use the underscore:
it clearly marks non-public members (type _ and intellisense will show you all the non-publics).
it prevents conflicts between local variables (which are often also written in camelCase), method parameters and non-public fields.
IMO both are a good reason to use the underscore, however I don't like how it makes my code look so I don't use it either. I prefer to use only camelCase when possible and I add a this. in case of conflicts with local variables or method parameters.
We simply try to keep the coding style consistent within the team and project.
Please see the last paragraph of the MS Field Usage Guidelines.
Do not apply a prefix to field names or static field names. Specifically, do not apply a prefix to a field name to distinguish between static and nonstatic fields. For example, applying a g_ or s_ prefix is incorrect.
No conventions prevent you from using valid identifier names. The important thing is to be consistent. I use "_" for all private variables, although the "right way" (for example ReSharper) seems to want you to declare them starting with a lowercase letter and differentiate between parameters and members trough the use of "this."
I don't really believe there is any BEST way to case variables and methods. What matters is that you and your team are consistent. The .NET naming conventions are great the way Microsoft specifies them, but some people prefer other conventions...
As a personal aside, I tent to prefix private variables and methods with "_" and then camel casing, protected variables and methods in camel casing and public variables and methods with pascal casing, but that is just me.
Yes, the naming convention enforced by StyleCop (which enforces the MS coding rules) is 'no underscores, camel case' for private instance fields.
It is of note that constant/static readonly fields have the 'Pascal case' naming convention (must begin with uppercase but not be screaming caps).
The other naming conventions are holdovers from C++ style, which was the initial style used to code C# in since that's where the C# team came from.
Important Note: Whether or not you use this coding style is entirely up to the development team. It's far more important that everyone on the team use the same style than that any particular style be used.
OTOH, MS chose this style after much deliberation, so I use it as a tiebreaker. If there's no particular reason to go one way or another with a coding style, I go the way StyleCop goes.

Should you always refer to local class variables with "this"

In C# you can refer to values in a class using the 'this' keyword.
class MyClass
{
private string foo;
public string MyMethod()
{
return this.foo;
}
}
While I presume the answer will likley be user preference, is it best practice to use the this keyword within a class for local values?
In the spirit of DRY, I would say this is not a particularly useful practice in general. Almost any use of this can be shortened to an equivalent expression by just removing the this.
One exception is if you have a local parameter which happens to have the same name as another class member; in that case you must distinguish between the two with this. But this is a situation you can easily avoid, by simply renaming the parameter.
I use the this keyword almost only when some member is hiding another, and when I need to pass the current class instance to a method for example:
class Employee
{
private string name;
private string address;
// Pass the current object instance to another class:
public decimal Salary
{
get { return SalaryInfo.CalculateSalary(this); }
}
public Employee(string name, string address)
{
// Inside this constructor, the name and address private fields
// are hidden by the paramters...
this.name = name;
this.address = address;
}
}
I would say it depends on personal preference for your own coding and on the team/company coding standards for your code at work. Personally, I try to keep both personal and "professional" coding standards the same--it reduces confusion, etc.
I prefer to use "this" on all class-level functions and variables. By using "this" you can immediately tell if the item is a class member or not. Also,I prefer to use "base" on members belonging to any base classes. It's not necessary, but it helps readability, esp if someone unfamiliar with your code is reading it.
I prefer this syntax. As the classes get larger and the functions get more complex, it is convenient to be able to read a variable name and know whether or not its an instance var without having to reference another part of the code.
Edit: I realize that if one is having trouble keeping track of variables, then it is probably time to refactor. This is fine in the abstract. So then to clarify: in the case where classes and their relationships aren't simple (and surely they exist) or in code where people have not refactored or followed good guidelines for keeping parameter names different from instance vars, I'll say (imho!) that using 'this' isn't a bad idea for clear code.
You're right - it's very much a preference thing. Of course, many companies enforce a set of coding style guidelines that either require this before any instance member, or require that it not appear. (Does anyone know what the Microsoft FxCop rules for the .NET framework are?)
Personally, I prefer to have this appear before any property, method or field that belongs to an instance. It makes it easier for me to distinguish where it belongs:
A member of an instance of the class (prefixed with this)
A static class member (which I prefix with the name of the class)
A local scope variable (no prefix)
It's more important to me to be able to read my code less ambiguously, than it is to save the 5 characters of this.. For instance, I immediately know that I need to dispose() all the local-scope items that were opened in this scope, and I won't confuse them with the instance-members that shouldn't be disposed. Heck, just for extra laziness points, I use this. as a quick way to access the intellisense list of member of the instance members.
In JavaScript, yes! In languages where it's not necessary, no. Some people do it to make the "memberness" visible to someone reading the code - but your IDE should be able to take care of that by highlighting it.
When VS 2010 comes out, my plan for world peace is to write an extension for the WPF code editor that displays this. in front of every reference to a member variable than doesn't already have that prefix. Then those who need that reminder will no longer need to type it, and those who don't like it can simply not install my extension and can freely delete any unnecessary this. prefixes they see.
I never use it. Mostly, it doesn't matter if a variable is a member or not. Keep your methods small enough that it's no problem to remember which variables are locals, and you won't mave so much trouble remembering which are members.
I use "_" as a prefix for member variables, as it is easy to ignore. But this means there will never be a collision with a local or parameter, so this. is not necessary.
My attitude may be "colored" by the fact that I use ReSharper, whose "color identifiers" mode makes it easier for me to see what's what.
I think that you should always include it if you are specifically referring to the class variable.
The reason for this is if you later on add in a local variable of the same name, you will need to rename all the class variables with this. so why not save your future self some time and hassle?

To underscore or to not to underscore, that is the question

Are there any problems with not prefixing private fields with an underscore in C# if the binary version is going to be consumed by other framework languages? For example since C# is case-sensitive you can call a field "foo" and the public property "Foo" and it works fine.
Would this have any effect on a case-insensitive language such as VB.NET, will there by any CLS-compliance (or other) problems if the names are only distinguishable by casing?
IMPORTANT UPDATE (December 12, 2022):
It really doesn't matter which notation you use. Just go with what is already used at your project or pick whatever for a new one. At the end of the day it's nitpicking and has nothing to do with how productive you are. Being flexible is your most important quality! You are a mercenary and you have to fight with any weapon you get.
So do not read the rest as it's very opinionated. And being an extremist doesn't help.
Peace!
IMPORTANT UPDATE (April 12, 2016):
It was brought to our attention that the internal standard of the .NET CoreFX team insists on using the underscore-notation without giving any insights as to why. However if we look closely at rule #3 it becomes evident that there is a system of _, t_, s_ prefixes that suggests why _ was chosen in the first place.
We use _camelCase for internal and private fields and use readonly where possible. Prefix instance fields with _, static fields with s_ and thread static fields with t_. When used on static fields, readonly should come after static (i.e. static readonly not readonly static).
We avoid this. unless absolutely necessary.
So if you are just like .NET CoreFX team working on some performance critical, multithreaded, system level code, then it is STRONGLY SUGGESTED that you:
adhere to their coding standards and
use the underscore-notation and
don't read this answer any further
Otherwise please read on...
THE ORIGINAL ANSWER:
Let's first agree on what we are talking about. The question is how we access instance members from within non-static methods and constructors of a class/sub-classes if visibility modifiers allow doing so.
Underscore-notation
suggests that you use the "_" prefix in the names of private fields
it also says that you should never use "this" unless it's absolutely necessary
This-notation
suggests that you just always use "this." to access any instance member
Why does this-notation exist?
Because this is how you
tell apart a parameter from a field when they share the same name
ensure you are working in the context of the current instance
Example
public class Demo
{
private String name;
public Demo(String name) {
this.name = name;
}
}
Why does the underscore-notation exist?
Some people don't like typing "this", but they still need a way to distinguish a field and a parameter, so they agreed to use "_" in front of a field
Example
public class Demo
{
private String _name;
public Demo(String name) {
_name = name;
}
}
One may think it's just the matter of personal taste and both ways are equally good/bad. However there are certain aspects where this-notation beats the underscore-notation:
Clarity
underscore-notation clutters names
this-notation keeps names intact
Cognitive load
underscore-notation is inconsistent, it makes you treat fields in a special way, but you cannot use it with other members, every time you need to ask yourself whether you need a property or a field
this-notation is consistent, you don't have to think, you just always use "this" to refer to any member
Maintenance
UPDATE: as was pointed out the following isn't an advantage point
underscore-notation requires you to keep an eye on _ while refactoring, say turning a field into property (remove _) or the opposite (add _)
this-notation doesn't have such problem
Autocompletion
When you need to see the list of instance members:
underscore-notation doesn't help you much, because when you type "_" the autocomplete popup shows you the private fields and all types available from the linked assemblies mixed with the rest of the instance members
this-notation gives you a clear answer, by typing "this" all you see is the list of members and nothing else
Ambiguity
Sometimes you have to deal with the code without help of the Intellisense. For example when you do code reviews or browse source code online.
underscore-notation is ambiguous: When you see Something.SomethingElse you cannot tell whether Something is a class and SomethingElse is its static property... or maybe Something is a current instance property which has its own property of SomethingElse
this-notation is clear: When you see Something.SomethingElse it can only mean a class with a static property and when you see this.Something.SomethingElse you know that Something is a member and SomethingElse is its property
Extension methods
You cannot use extensions methods on the instance itself without using "this."
underscore-notation requires that you don't use "this", however with the extension methods you have to
this-notation saves you from hesitation, you always use "this", period.
Visual Studio support
underscore-notation doesn't have a built-in support in Visual Studio
this-notation is supported by Visual Studio naturally:
"This." Qualification: Prefer all non-static fields used in non-static methods to be prefaced with this. in C#
Official recommendations
There a lot of official guidelines that clearly say "do not use underscores" especially in C#
underscore-notation came from C++ where it is a general practice which helps to avoid naming conflicts, also is recommended for VisualBasic.Net to overcome a problem where a field "value" and a property "Value" actually have the same name, because VisualBasic is case-insensitive
Declared element names in Visual Basic
Backing fields in VisualBasic.NET
this-notation is recommended for C# while "_" is explicitly prohibited:
this keyword in C#
Field usage guidelines: Do not apply a prefix to field names or static field names.
Guidelines for names: Names of type members: Do not use a prefix for field names.
General naming convention: X DO NOT use underscores, hyphens, or any other non-alphanumeric characters
Quality assertion rule CA1707: Identifiers should not contain underscores
Using underscores is not CLS compliant (for public and protected identifiers)
Internal naming convention of .NET Framework developers: Do not use a prefix for member variables. If you want to distinguish between local and member variables you should use "this." in C# and "Me." in VB.NET.
Taken from the Microsoft StyleCop Help file:
TypeName:
FieldNamesMustNotBeginWithUnderscore
CheckId:
SA1309
Cause:
A field name in C# begins with an underscore.
Rule Description:
A violation of this rule occurs when a field name begins with an underscore.
By default, StyleCop disallows the use of underscores, m_, etc., to mark local class fields, in favor of the ‘this.’ prefix. The advantage of using ‘this.’ is that it applies equally to all element types including methods, properties, etc., and not just fields, making all calls to class members instantly recognizable, regardless of which editor is being used to view the code. Another advantage is that it creates a quick, recognizable differentiation between instance members and static members, which will not be prefixed.
If the field or variable name is intended to match the name of an item associated with Win32 or COM, and thus needs to begin with an underscore, place the field or variable within a special NativeMethods class. A NativeMethods class is any class which contains a name ending in NativeMethods, and is intended as a placeholder for Win32 or COM wrappers. StyleCop will ignore this violation if the item is placed within a NativeMethods class.
A different rule description indicates that the preferred practice in addition to the above is to start private fields with lowercase letters, and public ones with uppercase letters.
Edit:
As a follow up, StyleCop's project page is located here: https://github.com/DotNetAnalyzers/StyleCopAnalyzers. Reading through the help file gives a lot of insight into why they suggest various stylistic rules.
It will have no effect.
Part of the recommendations for writing CLS-compliant libraries is to NOT have two public/protected entities that differ only by case e.g you should NOT have
public void foo() {...}
and
public void Foo() {...}
what you're describing isn't a problem because the private item isn't available to the user of the library
Since we are talking about a private field, it does not affect a user of your class.
But I recommend using an underscore for the private field, because it can make code easier to understand, e.g:
private int foo;
public void SetFoo(int foo)
{
// you have to prefix the private field with "this."
this.foo = foo;
// imagine there's lots of code here,
// so you can't see the method signature
// when reading the following code, you can't be sure what foo is
// is it a private field, or a method-argument (or a local variable)??
if (foo == x)
{
..
}
}
In our team, we always use an underscore prefix for private fields. Thus when reading some code, I can very easily identify private fields and tell them apart from locals and arguments. In a way, the underscore can bee seen as a shorthand version of "this."
After working in a environment that had very specific and very pointless style rules since then I went on to create my own style. This is one type that I've flipped back and forth on alot. I've finally decided private fields will always be _field, local variables will never have _ and will be lower case, variable names for controls will loosely follow Hungarian notation, and parameters will generally be camelCase.
I loathe the this. keyword it just adds too much code noise in my opinion. I love Resharper's remove redundant this. keyword.
6 year update: I was analyzing the internals of Dictionary<TKey,T> for a specific usage of concurrent access and misread a private field to be a local variable. Private fields definitely should not be the same naming convention as local variables. If there had been an underscore, it would have been incredibly obvious.
I like the underscore, because then I can use the lowercase name as method parameters like this:
public class Person
{
string _firstName;
public MyClass(string firstName)
{
_firstName = firstName;
}
public string FirstName
{
get { return _firstName; }
}
}
I still really like using underscores in front of private fields for the reason Martin mentioned, and also because private fields will then sort together in IntelliSense. This is despite the evilness of Hungarian prefix notations in general.
However, in recent times I find that using the underscore prefix for private members is frowned upon, even though I'm not quite sure why. Perhaps someone else knows? Is it just the prefix principle? Or was there something involved with name mangling of generic types that get underscores in them in compiled assemblies or something?
Style Cop recommendation or not, digging into the .NET Framework shows a lot of "_" usage for member variables. Whatever the creators of Style Cop recommend, it's not what majority of the MS employees are using. :) So I'll stick with the underscore. Because I personally make a lot less mistakes using the underscore then the this (example: using varName = varName instead of this.varName = varName, it's really stuck in me)
Update 2022
According to Microsoft documentation : C# Coding Conventions
Use camel casing ("camelCasing") when naming private or internal fields, and prefix them with _.
Benefit
When editing C# code that follows these naming conventions in an IDE
that supports statement completion, typing _ will show all of the
object-scoped members.
The _fieldName notation for private fields is so easy to break. Using "this." notation is impossible to break. How would you break the _ notation? Observe:
private void MyMethod()
{
int _myInt = 1;
return;
}
There you go, I just violated your naming convention but it compiles. I'd prefer to have a naming convention that's a) not hungarian and b) explicit. I'm in favor of doing away with Hungarian naming and this qualifies in a way. Instead of an object's type in front of the variable name you have its access level.
Contrast this with Ruby where the name of the variable #my_number ties the name into the scope and is unbreakable.
edit: This answer has gone negative. I don't care, it stays.
I think that by and large class-level fields are a mistake in the design of the language. I would have preferred it if C#'s properties had their own local scope:
public int Foo
{
private int foo;
get
{
return foo;
}
set
{
foo = value;
}
}
That would make it possible to stop using fields entirely.
The only time I ever prefix a private field with an underscore is when a property requires a separate backing field. That is also the only time I use private fields. (And since I never use protected, internal, or public fields, that's the only time I use fields period.) As far as I'm concerned, if a variable needs to have class scope, it's a property of the class.
When you want your assembly to be CLS compliant, you can use the CLSCompliant attribute in your assemblyinfo file.
The compiler will then complain when your code contains stuff that is not cls compliant.
Then, when you have 2 properties that only differ in case, the compiler will issue an error.
On the other hand, when you have a private field and a public property in the same class, there will be no problems.
(But, I also always prefix my private members with an underscore. It also helps me to make it clear when i read my code that a certain variable is a member field).
There are no implications whatsoever. When your code is compiled, all that is important to the compiler is the field/property's namespace and visibility. An underscore is just as significant as any other character when naming an identifier. The real trick is to use a convention that you and the people around you will understand.
Not to underscore. Because visually it looks too much like whitespace, not text. This affects readability of the indentation, which is how you understand the control flow of the code. [And it may needlessly trigger your carefully-honed badly-indented-code-detector reflex.]
Real world example...
{
Region = Environment.GetEnvironmentVariable(Dimensions.Names.REGION);
if (xyz)
{
InstanceId = Environment.GetEnvironmentVariable(Dimensions.Names.INSTANCEID);
_rawData = (long)0; // Disabled by default
}
_additionalDimensions = new Dictionary<string, string>();
}
vs.
{
Region = Environment.GetEnvironmentVariable(Dimensions.Names.REGION);
if (xyz)
{
InstanceId = Environment.GetEnvironmentVariable(Dimensions.Names.INSTANCEID);
rawData = (long)0; // Monitoring disabled by default
}
additionalDimensions = new Dictionary<string, string>();
}
I like to use underscores in front of my private fields for two reasons. One has already been mentioned, the fields stand out from their associated properties in code and in Intellisense. The second reason is that I can use the same naming conventions whether I'm coding in VB or C#.

How do you name constructor argument and member variables?

I don't use prefix while naming internal variables of a class (I know some do but I am not starting "why do you..." debate). I just prefer it that way. The problem is that sometimes same parameters are passed in contructor and I end up being confused how to name them. For example:
public class SampleClass
{
private int classId;
private string className;
public SampleClass (int XclassIdX, string XclassNameX) {
classId = XclassIdX;
className = XclassNameX;
}
}
How to name XclassIdX and XclassNameX?
One thing that can probably be done is:
public class SampleClass
{
private int classId;
private string className;
public SampleClass (int classId, string className) {
this.classId = classId;
this.className = className;
}
}
Just not sure whether this is a good idea or there are other more elgant ways?
I think the solution you're describing, where the constructor parameters are identically named and you prefix the class members with this, is just fine. It's clear, it's concise, and there is no confusion about what you meant.
I simply use the this approach; then all my variables and fields reflect their intent. Don't do the X thing - that is just ugly ;-p
I cases like this, I don't think any one way is better than any other. But for the sake of other people who might need to maintain your code (and yourself for that matter) I'd say just pick one way of doing it and be consistent about it.
Short answer:
Prefix members and parameters with "m_" and "p_", or "s_" if member is static.
Don't decorate properties or locals, and when you feel you must name them the same (ignoring case), resolve the conflict by prefixing properties with "this.".
Explanation:
Consider that there are at least FOUR(4) different categories of readable/assignable names that need distinguishing: Local variables, Member variables (instance and static), Properties, and method Parameters. All four categories may appear in a single code block, and therefore they each need clear distinguishing characteristics.
A meaningful prefix can simultaneously distinguish variables and reveal their scope such as m_(member), s_(static), p_(parameter), leaving public properties and local variables to remain simple without prefixes and without worrying about case sensitivity. If for some reason you must name a local the same as a property without regard to case, then simply prefix the property with "this."
Naming conflicts between Local variables and Parameters don't occur, because they cannot be named the same thing (compiler will catch the duplicate definition). The same goes for Member variables and Properties. Parameters and members prefixed with "p_" and "m_" respectively will not conflict, and conflicts between non-prefixed locals and properties can be resolved by adding "this." to the properties.
The alternatives to my suggestions are not pretty: use case sensitivity (bad idea, as not all CLR languages are case sensitive), use underscores by themselves (also bad, as it may collide with standards and doesn't tell you a damn thing), or use different names altogether (can be time consuming, difficult, and appear arbitrary).
Why not just add an underscore or single letter prefix for your private member variables.
If you don't like that idea, what you've done in your second code block is ok.
Putting X on your parameters like that is bad. The constructor is part of the public interface of your class and it will only confuse the users of your class. Some like to prefix the member variables with underscores which is much better as it is only visible to the implementor of your class. Otherwise using this as in your second example will suffice.
m_foo for private members
Foo for public property
foo for parameters and local variables.
I prefer to distinguish the block scope from the extended scope members, that's why I stick with the prefix.
You need to separate them in some way. Using 'this.' is a weak form of hungarian notation so you might as well bite the bullet and use underscores or 'm_' .
I also feel 'this.' is actually worse because in extreme cases (i.e. large methods) it is possible the 'this.' will be left off and the wrong variable will be referenced. I know large methods are bad but they do occur naturally in real business applications with developers of varied skill. Using a prefix for private fields will prevent that scenario.
It is tempting to argue that the underscore may be forgotten in the same way as 'this.' would. But that is incorrect because the underscore changes the name of the variable, so the only place it could possibly be forgotten is at the definition, not at it's usage within the file. Whereas with the 'this.' prefix there is no compiler error if you forget it during usage.
Whatever you choose, there's no avoiding hungarian in this situation whether you use 'this.' or underscore. It's not so bad anyway, we are forced by convention to use hungarian for interface names, control names and probably other places I can't think of right now.

Categories