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
Unluckily there are no common convention, you have to choose what suits most your case, I've seen all the following approaches in different codebases.
Approach 1
private string _fubar; //_camelCase
public string Fubar { ... }
Approach 2
private string fubar; //camelCase
public string Fubar{ ... }
Approach 3
private string _Fubar; //_PascalCase
public string Fubar{ ... }
Also there are frameworks that takes much creativity like using a property and document it as a member variable and thus using member's styling instead of the properties' styling ( yeah Unity! I'm pointing the finger at you and your MonoBehaviour.transform
's property/member)
To disambiguate in our code base we use our homemade rule:
With our approach most times we avoid the doubt about the underscore "_" while at same time having a much more readable code.
private string fubarValue; //different name. Make sense 99% of times
public string Fubar { ... }
Another way to declare with a default value
private string _fubar = "Default Value";
public string Fubar
{
get { return _fubar; }
set { _fubar = value; }
}
I thing, one name is better:
public string Fubar { get; private set; }
While most developers follow Microsoft's guideline, as game developers, we follow Unity's style as (one of the script source code here):
static protected Material s_DefaultText = null;
protected bool m_DisableFontTextureRebuiltCallback = false;
public TextGenerator cachedTextGenerator { ... }
I see a ton of outdated answers (and non-standard ways representing C#6), so this one's for 2020:
// "fubar" works, too, but "_" prevents CaSe typo mistakes
private string _fubar;
public string Fubar
{
get => _fubar;
set => _fubar = value;
}
// Read-only can just use lambda to skip all those shenannigans
public string ReadOnlyFoo => "This is read-only!";
If there's no logic in the getter/setter, use an auto-property:
public string Fubar {get; set;}
http://msdn.microsoft.com/en-us/library/bb384054.aspx