What is differance between int _a and int a
i try lot of googling but unablre to get answer
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
vaibhav bhargavPosted Nov 24, 2011, 6:46 AM
Sam HobbsPosted Nov 24, 2011, 5:57 AM
So why am I talking about C and C++ when your question is about C#? Because the C# language is very much like C++. There are many variations used for making a variable's name unique; one way is to use the leading underscore. There is absolutely nothing that requires use of a leading underscore but it is one of very many alternatives that some developers use. In C++ Microsoft uses "m_" as the prefix for members of a class. Some developers might use "my". I wish someone would design a better way of doing it but the syntax of a solution is not simple and obvious.
VulpesPosted Nov 24, 2011, 5:50 AM
VulpesPosted Nov 24, 2011, 5:27 AM
The data cannot be accessed directly but only through the property which can make sure that you don't assign values which are invalid, carry out subsidiary calculations and so forth.
Suppose, for example that you wanted '_a' to only be assigned values of between 0 and 9 inclusive. You could achieve that with the following property:
class MyClass
{
int _a;
public int A
{
get { return _a; }
set
{
if (value < 0 || value > 9) throw new ArgumentException("Value must be between 0 and 9");
_a = value;
}
}
}
For this reason, properties are sometimes called 'smart fields'.
vaibhav bhargavPosted Nov 24, 2011, 4:59 AM
VulpesPosted Nov 24, 2011, 4:45 AM
So _a and a are different variables.
It's common when declaring private fields in a class to precede the field name with an underscore and then expose it via a public property which begins with an uppercase letter. For example:
class MyClass
{
int _a;
public int A
{
get {return _a; }
set { _a = value; }
}
}