Chris
Chris

Reputation: 8422

Constructors and throwing exceptions

Is this the best way for me to abort instantiation of an object if it's parameters are not passed in with valid data?

protected Command(string commandKey)
{
    if(commandKey == null) throw new ArgumentNullException("commandKey", "Command Key cannot be null as it is required internally by Command");
    if(commandKey == "") throw new ArgumentException("Command Key cannot be an empty string");
    CommandKey = commandKey;
}

Upvotes: 2

Views: 145

Answers (5)

Peeyush
Peeyush

Reputation: 4828

It is perfectly fine if you validate inside a constructor and throw exception if something goes wrong.

Upvotes: 0

competent_tech
competent_tech

Reputation: 44931

This is exactly what Microsoft does if you look through the framework source code, so I suspect it is perfectly valid.

Upvotes: 0

Dominik Weber
Dominik Weber

Reputation: 427

In this case you could use the static method string.IsNullOrEmpty(commandKey):

protected Command(string commandKey) 
{ 
    if(string.IsNullOrEmpty(commandKey))
        throw new ArgumentException("commandKey");
    //something
} 

Upvotes: 0

FailedDev
FailedDev

Reputation: 26930

It's perfectly fine. Constructors do not return anything so how else would you know if something went wrong? You could have a bool to set it to some uninitialized state but I would go with exceptions.

Also :

if(String.IsNullOrEmpty(commandKey)) //throw exectpion

Upvotes: 0

dtb
dtb

Reputation: 217283

Yes. It is common practice to validate the arguments in constructors and throw an exception if they are invalid.

Upvotes: 1

Related Questions