0

I have a big hierarchical object and I want one propertie from this structure. The problem is, every level of that object could be null. (It's data from a structured XML)

I want something like this:

_data = record.RltdPties.DbtrAcct.Id.Item

if one of this sub object is null, the data should be also null. Is there a better way the validate my object instead of this:

if(record!=null && record.RltdPties != null && record.RltdPties.DbtrAcct != null && record.RltdPties.DbtrAcct.Id != null)
{
     _data = record.RltdPties.DbtrAcct.Id.Item
}

I could make a try{} catch{} block, but that's not a good solution.

wydy
  • 71
  • 12

3 Answers3

2

with c# 5.0

_data = record?.RltdPties?.DbtrAcct?.Id?.Item
tire0011
  • 1,048
  • 1
  • 11
  • 22
1

I think a try-catch-block would be the absolute right solution here, because you have to check the whole tree down and it does not look like there are any possible branches in the path of objects. It may not be C#-like but sometimes EAFP (easier to ask forgivenes than permission) keeps it simple enough.

try 
{
  _data = record.RltdPties.DbtrAcct.Id.Item
}
catch NullReferenceException
{
  // do whatever then to do
}
Oliver Friedrich
  • 9,018
  • 9
  • 42
  • 48
0

If you can use C# 6.0, you could use the null conditional operator. http://www.codeproject.com/Articles/850832/What-s-new-in-Csharp-Null-conditional-operators

enter image description here

In your case it would be _data = record?.RltdPties?.DbtrAcct?.Id?.Item

cverb
  • 645
  • 6
  • 20
  • what would be stored in _data if e.g. DbtrAcct is null? would _data be null or the contents of RltdPties? – Oliver Friedrich Aug 04 '15 at 11:59
  • _data would be null. The null conditional operator must be interpreted as 'if the object on the left is not null, fetch whatever that is on the right, otherwise return null'. – cverb Aug 04 '15 at 12:04