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?
Check the value in your first constructor, and have the second constructor do a pass-through to it in order to avoid duplicate code.