ElConrado
ElConrado

Reputation: 1640

Checking whether nested/hierarchy of properties are null?

I have:

label.Text = myObject.myNestedObject.MyNestedObject2.Description;

Where label is asp.net label. The problem is that sometimes myObject, myNestedObject, MyNestedObject2 or Description is null and I must check it in if statement which looks like:

if(myObject!=null&&myNestedObject!=null&&MyNestedObject2!=null&&Description!=null)
{
label.Text = myObject.myNestedObject.MyNestedObject2.Description;
}

In this statement I check four times whether properties is null. Does exist any other way to check entire hierarchy?

Upvotes: 2

Views: 504

Answers (1)

Sam Axe
Sam Axe

Reputation: 33738

C# null-conditional operators to the rescue!

Taken from the MSDN site:

int? length = customers?.Length; // null if customers is null 
Customer first = customers?[0];  // null if customers is null
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null

Upvotes: 1

Related Questions