Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Properties - Set question

Tags:

c#

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 :-/

like image 1000
Ryan Rodemoyer Avatar asked May 27 '09 14:05

Ryan Rodemoyer


1 Answers

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.

like image 196
Adrian Godong Avatar answered Oct 15 '22 22:10

Adrian Godong