I'm working in C# and I'm starting to play with properties. One thing I don't know is what is the best way/where to put the logic for the set accessors of class properties and how to handle the errors.
For instance, say I have this (basic) class:
class Person
{
private int _Age = 18;
public Person()
{
}
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
}
Now say I have a requirement on the Age property, 0 < Age < 100. Where do I put the logic for this?
Should I put it in the property?
public int Age
{
get
{
return _Age;
}
set
{
if (value < 0 || value > 99)
// handle error
else
_Age = Convert.ToInt32(value);
}
}
or through class that is creating a Person object?
static void Main(string[] args)
{
Person him = new Person();
int NewAge = -10;
if (NewAge < 0 || NewAge > 100)
// handle error
else
him.Age = NewAge;
}
Now what if there is a problem with the NewAge (it doesn't meet my constraint)? Should I create a custom exception and throw that? Should I just print a message saying supply a valid age?
I've done some Googling and I cannot find anything that fully answers my questions. I need a book :-/
Use the property setter, it is there for that reason (adding functionality to a field).
If out of range value is passed in, you can throw ArgumentOutOfRangeException or just set it to minimum (or maximum) value, but this depends on your process requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With