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.
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.
VulpesPosted Oct 7, 2013, 2:56 AM
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; }
shilpaka anjinappaPosted Dec 4, 2013, 4:38 AM
Santosh YadavPosted Oct 19, 2013, 3:57 AM
VulpesPosted Oct 18, 2013, 6:42 PM
Santosh YadavPosted Oct 18, 2013, 3:58 PM
Posted Oct 7, 2013, 3:16 AM
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