The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use.
Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable.
Variable names can never contain spaces. The underscore character ( _ ) can also appear in a name.
Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
There's no language-defined meaning - it's just a convention some people use to distinguish instance variables from local variables. Other variations include m_foo (and s_foo or g_foo or static variables) or mFoo; alternatively some people like to prefix the local variables (and parameters) instead of the instance variables.
Personally I don't use prefixes like this, but it's a style choice. So long as everyone working on the same project is consistent, it's usually not much of an issue. I've seen some horribly inconsistent code though...
In general, this means private member fields.
The underscore before a variable name _val
is nothing more than a convention. In C#, it is used when defining the private member variable for a public property.
I'll add to what @Steven Robbins said:
private string _val;
public string Values
{
get { return _val;}
set {_val = value;}
}
A lot of people use them for property private variables (the variables that actually store the values for public properties).
There is another advantage with starting an instance property with '', it shows up first on Intellisense.
When creating a value/model/POCO class, I don't using ''.
I know this is a little old, but in case anyone ends up here I'll add to the answers here that if you are talking about MVC on .NET, also there is a naming convention on partial views also with their names starting with underscore.
This are naming conventions that you and your team can decide to follow or not, as long as all of you are aware of the decision. I use them also with non public fields like private or protected just to recognize them.
Here's a little brief about it if you want to read further.
The use of an underscore for property private variables is very useful in avoiding situations where you may accidentally call the variable and not the property within the class itself. (Easily done with a simple lowercase intellisense input)
If you undertake some form of calculation or aggregation within the property get{} the last thing you want to do is miss this when your intention is to call the property in full.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With