Sir, I need your help in the following:-
I declare a member variable as private. Then provide access to them with public modifier,
what is the benefit of declaring a member variable as private?
could you give me a example?
Loading
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 Oct 6, 2013, 10:56 PM EDT
It is considered better to declare the field to be private and then controlling access to it using a public property. That way you can make sure that the user doesn't assign an invalid value to it.
For example:
class Person
{
int _age;
public int Age
{
get { return _age; }
set
{
if (value < 0 || value > 125)
throw new ArgumentException ("Age must be be between 0 and 125");
else
_age = value;
}
}
}
Even when the argument is not checked for correctness, it's still considered better to use properties in case checking is introduced at a later stage. If you have to change from a field to a property, this changes the public interface of your class.
At one time, this used to be quite tedious and lead to code bloat but since the introduction of automatic properties it's no longer a problem:
public string Name { get; set; }
Posted Oct 6, 2013, 11:16 PM EDT
for example: if your create the object of that class in which private variable is exist. the private variable will not be access to that object
Santosh YadavRank #6,715 · 258 reputationPosted Oct 18, 2013, 11:58 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 18, 2013, 2:42 PM EDT
Santosh YadavRank #6,715 · 258 reputationPosted Oct 18, 2013, 11:57 PM EDT
shilpaka anjinappa25 reputationPosted Dec 3, 2013, 11:38 PM EST