Let\'s say, we have a variable, which we want named Fubar
Let\'s say that Fubar
is a String
!
That means, we would define F
The nice thing about coding standards is that there are so many to choose from:
Pick a convention that suits you and use it consistently.
The Microsoft convention — pascalCase private fields and CamelCase properties is tidy, but can lead to bugs due to typos. I find the leading underscore convention annoying as it requires two additional key strokes every time you type the name, but you don't get the typos so much (or at least the compiler catches them first).
prefix the private with an underscore _Fubar
The c# way is
private string _fubar;
public string Fubar
{
get
{
return _fubar;
}
set
{
_fubar = value;
}
}
However, if it's just a basic getter/setter with no extra logic, you can just write
public string Fubar { get; set; }
No need for a backing variable or anything.
Per Microsoft's naming conventions, the proper way would be:
private string fubar;
public string Fubar { get { return fubar; } set { fubar = value; } }
However, many people prefer to prefix the private field with an underscore to help minimize the possibility of miscapitalizing and using the field when they meant to use the property, or vice versa.
Thus, it's common to see:
private string _fubar;
public string Fubar { get { return _fubar; } set { _fubar = value; } }
The approach you take is ultimately up to you. StyleCop will enforce the former by default, whereas ReSharper will enforce the latter.
In C# 6, there is new syntax for declaring default values for properties or making read-only properties, lessening the need for properties with backing fields that don't have any special additional logic in the get
and set
methods. You can simply write:
public string Fubar { get; set; } = "Default Value";
or
public string Fubar { get; } = "Read-only Value";
If you name your private variables starting with lower case, you can right click on them and have VS generate your getter/setter code for you;
Refactor->Enacpsulate Field...
It will name the property with Caps.
Well, the Framework Design Guidelines document states the following:
Names of Fields The field-naming guidelines apply to static public and protected fields. Internal and private fields are not covered by guidelines, and public or protected instance fields are not allowed by the member design guidelines.
✓ DO use PascalCasing in field names.
✓ DO name fields using a noun, noun phrase, or adjective.
X DO NOT use a prefix for field names.
For example, do not use "g_" or "s_" to indicate static fields.
So, for private fields, there is no official recommendation. However, if you use VS 2017 quick action "Convert to full property" on a property, this happens:
So it seems like it is safe to assume that prefixing private fields with an underscore is somewhat standard.