So I have a class with a single string parameter in its constructor:
public MyClass(string name)
{
this.Name = name;
}
but I never want to worry about some one initializing an instance of MyClass with name that is NULL or a zero length string. What is the best was to validate the parameter? With a property or method you can always just do nothing, return null, or not set anything if an invalid argument is provided. But once a constructor is called the instance of the object is already created regardless of whether it was passed valid arguments.
Is throwing an exception as shown below the best way? Or is there some other method that's more preferred?
public MyClass(string name)
{
if (name == null | name == "") throw new ArgumentException("Name can not be null or blank", "name");
this.Name = name;
}
Of course I could always set the name to some default like "Unnamed MyClass" if the argument is invalid, but in this case I'd rather just prevent an invalid name then trying to assume some alternate behavior.
ArgumentNullException
ArgumentNullException
if name is null
Edit: Instead of this:
if (name == null || name == "")
Use this:
if (string.IsNullOrEmpty(name))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With