I have a class Person
which I need to have a property/field Age
.
I want Age to be readable anywhere, but only Grow()
should be able to change it's value.
If I make Age
public, then it can be modified from outside, so it won't work for me.
Making it private prevents being read from outside.
I also tried making it an autoproperty with only a get method, but then the variable becomes readonly and can only be set in the construtor.
Of course I can make Age private
and create a function int GetAge()
which returns Age
.
The problem here is that if my class has a lot of such fields I have to create a get function for each of them.
Is making the function int GetAge()
the only way of solving this, or there's somethig else that allows to easily have properties or fields readable but not writable from outside the class?
class Person
{
private int _age;
Person(int age)
{
_age = age;
}
void Grow()
{
_age ;
}
int GetAge()
{
return (_age);
}
}
CodePudding user response:
Properties can have individual access descriptors for read and write. So, your class can be:
public class Person
{
public int Age {get; private set; }
public Person(int age)
{
Age = age;
}
public void Grow()
{
Age ;
}
}
If you only set Age
in the constructor, and did not change it in any of the methods, you could have declared it as public int Age {get;}