I have a method that has many many statements like this:
employee.LastName = file.EMPLOYEE.NAME.SUBNAME.FAMILYNAME.NAMEPART1.Value;
(This is a made up structure. The actual structure is based off of 2.3 HL7 XML and is far more complex and full of pointless objects.)
So my problem is that any one of these values can be null. If I don't check that then when I try to get the next value in the chain it will throw an exception.
Obviously I could do something like this:
if (contract.EMPLOYEE != null)
if (contract.EMPLOYEE.NAME.SUBNAME != null)
if (contract.EMPLOYEE.NAME.FAMILYNAME != null)
if (contract.EMPLOYEE.NAME.FAMILYNAME.NAMEPART1 != null)
employee.LastName = file.EMPLOYEE.NAME.SUBNAME.FAMILYNAME.NAMEPART1.Value;
But that is a lot of checks for each time I need to set a value. (And the object tree changes a lot so I cannot do a check it once and be done system.)
Maybe the better way is to do this:
try
{
employee.LastName = file.EMPLOYEE.NAME.SUBNAME.FAMILYNAME.NAMEPART1.Value;
}
catch
{}
(Note if the value is not there then I am fine to not have nothing done.)
However, this is a bit messy still. I have 14 items to set in this method alone and many many more to come.
Is there a way I can abstract this so I can just do my setters and little else?
I thought of a method call that would do the checks/try statement, but if I pass in file.EMPLOYEE.NAME.SUBNAME.FAMILYNAME.NAMEPART1.Value
it will try to resolve it while I pass it (thus giving me an exception).
Is there some other (clean) way? (Maybe an extension method would work?) I would be grateful to any ideas.
Note: I ended up just doing this for each line:
try { employee.LastName = file.EMPLOYEE.NAME.SUBNAME.FAMILYNAME.NAMEPART1.Value; } catch (System.NullReferenceException) { }
It seems more readable than the lambda system.