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.
Related
I've always been in the habit of defining constants at the class level:
public class MyClass
{
private const int SomeNumber = 10;
...
}
But, I recently worked with someone who believes that if a constant is only used by a specific method it should be defined in that method:
public class MyClass
{
public void SomeMethod()
{
const int SomeNumber = 10;
...
}
}
My only argument for preferring the first is that if the constant is needed in other methods there is no refactoring needed and also it makes it easier to update constants since they'll be defined in the same place.
Are there any other pros/cons or is there no real difference?
If it needs updating it's not really a constant. I mean, you don't often refactor the value of Pi. Things that change belong in a configuration file in my opinion.
That said, I usually use class level public constants.
I've never seen or used method-level constants. Conceptually, a method level constant makes little sense to me.
A common reasoning against globals, singletons, etc. is that the scope of everything should be limited as far as (reasonably) possible. I agree - the smaller the scope, the less code can break when someone messes with it and the less code can mess with it. This reasoning doesn't quite apply to constants. But still, if it is only needed in a single method, define it there. If only to prevent some fool from using it in a completely unrelated context because it happens to fit, breaking stuff when the "constant" does change (which shouldn't be often - otherwise it's not a constant but should go in a configuration file - but still).
As for "less refactoring if other methods need to access the constant"... YAGNI.
The method level const hints to the compiler that the variable will not change so it can optimize for that case. Which is great if you are in the habit of hard-coding strings or numbers into your methods that are not used outside those methods. Which is not, imho, a good habit.
i would go with your approach of defining at least at class level. so that same constant can be seen by various methods of class.
or even better approach
define all constant in a single class so that all those constants can be seen by differnt classes through out your solution eevn if you want to change some logic in the constant calculation you can do it at a centrilized place.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why does StyleCop recommend prefixing method or property calls with “this”?
When do you use the “this” keyword?
Hi SO, and happy Friday
I have a question regarding the use of this.method();. My code seems to work without using the this., but I include it because it seems like the right thing to do. When should .this be used, and because it's presence doesn't always make a difference, what's the best practice for .this?
My opinion: use this for disambiguation purposes, e.g., when a parameter name collides with a class property, otherwise leave it out for less noise.
For the pure sake of readbility and understandabilitly you should always use the this. whenever you call an instance member. It is considered best practice and StyleCop suggests it too:
(With the this prefix) all calls to class
members (are) 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 are not be prefixed.
A final advantage of using the ‘this.’
prefix is that typing this. will cause
Visual Studio to show the IntelliSense
popup, making it quick and easy for
the developer to choose the class
member to call.
In other words, if you omit the this. prefix you can not quickly understand, wether soemthing is a static member, a local variable, a delegate ... With the prefix you'll see it at first glimpse.
But the most important thing is: Whatever you chose, you should keep it consistent across the whole file, and across all other files and propably also across your whole team !
You've got two disagreeing answers so far so I'll add my perspective as an ex-Java, ex-C# and now a mostly-Python programmer. In Python we have self that does pretty much the same job, just it's not optional.
I would say use this as often as you can. It doesn't change anything as it's implicit when you call it from within an object but it does help differentiate so you know you're calling a class member (vs a global function).
You'll appreciate it when you read over the code in a year's time.
You don't need it if the call is not ambiguous, but I prefer using it, too. In my opinion, it is simply consistent for Bar to access properties and methods of Foo by foo.Property and foo.Method(), and access its own members as this.Property and this.Method(). You're still dealing with properties and methods of objects, except in the case of this, you're dealing with members in the same class. But why should that matter regarding coding style?
I use this all the time. It's clean, it's clear, and it's consistent.
When referring to a variable, this. can distinguish between a local variable or a parameter, and a member variable. But when referring to a method, it doesn't offer any useful distinction, and is therefore, to my way of thinking, codejunk. Leave it off.
Effectively the this keyword used in the context you describe is most useful as a disambiguator if you have more that one item in scope with the same name (e.g. an instance variable and a local variable of the same name)
one way you really need it is when pass a parameter named as the member
in constructors
Myclass(int id)
{
this.id = id;
}
I normally don't leave 'this.' in code at all. But I do use it for intellisense purposes when I can't remember what 'this.' contains. Then I remove it.
But one instance you have to keep it, is to qualify members hidden by similar names. For example:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
Several people have mentioned the use of this with regard to member variables. I would recommend...
Either:
Prefix member variables with this.
Or:
Adopt a naming convention for member variables that requires you to name them with a _leadingUnderscore
Stylecop rules can be set to enforce whichever of these rules your team prefers.
This points to the current object, it's basically used to remove the ambiguity of
method/variable names for e.g.
public class Test
{
private string name;
public Test(string name)
{
this.name = name;//using this coz the parameter name and variable names are same
}
}
You don't need to use it always.
I hope it helps you.
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?
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#.