0

Possible Duplicate:
Mark parameters as NOT nullable in C#/.NET?

For example, I have a simple class with one field:

class User
{
    private readonly string _name;

    public User(string name)
    {
        _name = name;
    }

    public string Name { get { return _name; } }
}

How to forbid to set name argument to null, because User should always have some name? I can't to do such check inside constructor, because anyway instance will be created. Should I use some pattern (make private constructor and add method to generate instances... don't know how this pattern called) or there is any language support to do this trick?

Thanks.

Community
  • 1
  • 1
kyrylomyr
  • 12,192
  • 8
  • 52
  • 79

2 Answers2

5

Do the check in the constructor: if the name argument is null then throw an ArgumentNullException.

I can't to do such check inside constructor, because anyway instance will be created.

An object instance will not be created if the constructor throws an exception so you don't have to worry about having an invalid user:

User user = null;

try
{
     user = new User(null); //throws ArgumentNullException
}
catch (ArgumentNullException)
{
    //user == null is true.
}
InBetween
  • 32,319
  • 3
  • 50
  • 90
3

There are two solutions:

  • Throwing exception at constructor in case of a NULL value. This is generally considered a bad thing. (According to Jeffrey Richter's book)
  • Code contracts
Aliostad
  • 80,612
  • 21
  • 160
  • 208