Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a value in property

So I heard that validating a value in a property like this:

//dummy example, let's assume that I want my value without dots
public string MyProp
{
    set
    {
        if(value.Contains('.'))
            throw new ArgumentException("Must not contain '.'", "value");
    }
}

is wrong and I should avoid it.

But in earlier days I was told that this is the good way. We could use encapsulation, there is just one place to check, DRY, etc.

What's wrong with my little example?

like image 850
ramires.cabral Avatar asked Apr 08 '13 17:04

ramires.cabral


Video Answer


1 Answers

There is nothing wrong with throwing exceptions in a property setter. But you should throw an ArgumentException, and also actually set the value of the property!

private string _myprop;
public string MyProp{
    set{
       if(value.Contains('.')) throw new ArgumentException("Must not contain .");
       this._myprop=value;
    }
    get { return this._myprop; }
}

From an article on best practices in MSDN:

Property getters should be simple operations without any preconditions. If a getter might throw an exception, consider redesigning the property to be a method. This recommendation does not apply to indexers. Indexers can throw exceptions because of invalid arguments.

It is valid and acceptable to throw exceptions from a property setter.

like image 183
Julián Urbano Avatar answered Nov 15 '22 13:11

Julián Urbano