Constructor parameter validation in C# - Best practices

Posted by MPelletier on Programmers See other posts from Programmers or by MPelletier
Published on 2011-02-23T18:56:31Z Indexed on 2011/02/23 23:33 UTC
Read the original article Hit count: 631

Filed under:
|
|

What is the best practice for constructor parameter validation?

Suppose a simple bit of C#:

public class MyClass
{
    public MyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
            throw new ArgumentException("Text cannot be empty");

        // continue with normal construction
    }
}

Would it be acceptable to throw an exception?

The alternative I encountered was pre-validation, before instantiating:

public class CallingClass
{
    public MyClass MakeMyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
        {
            MessageBox.Show("Text cannot be empty");
            return null;
        }
        else
        {
            return new MyClass(text);
        }
    }
}

© Programmers or respective owner

Related posts about best-practices

Related posts about c#