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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Nov 23, 2011, 11:45 PM EST
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; }
}
}
vaibhav bhargav96 reputationPosted Nov 23, 2011, 11:59 PM EST
VulpesRank #55 · 29.2K reputationPosted Nov 24, 2011, 12:27 AM EST
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'.
VulpesRank #55 · 29.2K reputationPosted Nov 24, 2011, 12:50 AM EST
Sam HobbsRank #107 · 20.5K reputationPosted Nov 24, 2011, 12:57 AM EST
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.
vaibhav bhargav96 reputationPosted Nov 24, 2011, 1:46 AM EST