earthling
earthling

Reputation: 5264

Validating constructor parameters

I have a class with two constructors:

MyObjGroup(MyObj primaryObj)
MyObjGroup(MyObj primaryObj, MyObj secondaryObj)

primaryObj is always required. secondaryObj is not. Obviously you can call MyObjGroup(myObj) or MyObjGroup(myObj, null) and end up with the same result.

What I first considered doing was in my first ctor, checking for null on primaryObj and throwing a ArgumentNullException. I would also need to do this in my secondary ctor, duplicating the code, so I considered moving this to the property setter.

private MyObj _primaryObj;
public MyObj PrimaryObj
{
    get {return _primaryObj;}
    private set
    {
       if(value == null) throw new ArgumentNullException("value", "PrimaryObj cannot be null");
        _primaryObj = value;
    }
 }

however, the name of the parameter in the property is value while in the ctor it is called primaryObj. Another ctor (heaven forbid) may call it something else so there is no guarantee you have the correct name.

what is the recommended course of action here?

Upvotes: 1

Views: 118

Answers (2)

Steen Tøttrup
Steen Tøttrup

Reputation: 3835

I always put the logic in as few constructors as possible, so I would do this:

public MyObjGroup(MyObj primaryObj) : this(primaryObj, null) { }

public MyObjGroup(MyObj primaryObj, MyObj secondaryObj) {
    if (primaryObj == null) {
        throw new ArgumentNullException("value", "PrimaryObj cannot be null");
    }
    SecondaryObj = secondaryObj;
    PrimaryObj = primaryObj;
}

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156524

Check the value in your first constructor, and have the second constructor do a pass-through to it in order to avoid duplicate code.

public MyObjGroup(MyObj primaryObj) 
{
    if(primaryObj == null) 
        throw new ArgumentNullException("value", "PrimaryObj cannot be null");
}

public MyObjGroup(MyObj primaryObj, MyObj secondaryObj) 
    : this(primaryObj)
{
    SecondaryObj = secondaryObj;
}

Upvotes: 3

Related Questions