Null coalescing operator (??) example in C# and using it with LINQ & XML

The ?? operator can be very useful in these scenarios.

For example, let’s consider a scenario where we have an XML file or feed with the following contact data:

We could write the below LINQ to XML code in C# to open the XML file and retrieve back a sequence of anonymous type objects with “Name”, “Title”, “Email” and “YearsAtCompany” properties, and then databind the results to an control on a page:

Notice above how I’m using the explicit conversion operator support on the XElement class to retrieve strongly typed values from the XML.  This enables me to just cast the c.Element(“YearsAtCompany”) value to an int – and it will then automatically convert the string value to an integer for me, and type the “YearsAtCompany” property on my anonymous type to be an int.

When we run the above code snippet, we’ll then get a nice Gridview listing of our contacts:

This explicit conversion support works great when the <YearsAtCompany> element is always defined.  But it will throw a runtime error in the case where we have a that is missing a sub-element:

One way to fix this is to modify our LINQ to XML query so that we indicate that YearsAtCompany is a nullable integer.  We can do this by changing the explicit cast to be (int?) instead of (int):

This enables our query to execute cleanly and not raise any errors.  Instead a null value will be assigned to the YearsAtCompany property if no element is present in the XML.

When we run the application and databind the results to the Gridview, you can see the YearsAtCompany column for our third contact is empty as a result (since the value is null):

But what if we didn’t want a missing XML value to result in a null integer value – but instead just indicate a value of 0?

Well…. that is where we can use the new ?? operator support.  We can just modify the LINQ to XML query like below to indicate a default value of 0 if no element is present:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s