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.
Do the check in the constructor: if the
nameargument isnullthen throw anArgumentNullException.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: