Easy Way to Perform C# Null Check in a Type Conversion

1.1k views Asked by At

I am doing some quick type conversions in a project I am not that very familiar with.

They look similar to this:

var NewType = new
{
    NewTypeId = old.SubType == null ? 0 : old.SubType.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country == null ? "" : old.Country.Abbreviation ?? "",
    Customer = old.SubType == null ? "" :
                    old.SubType.Customer == null ? "" :
                        old.SubType.Customer.Name ?? ""
};

The objects I'm converting are usually Entity Framework objects. I also don't have the ability to modify the classes I will be converting form.

Is there an easier way to check for nulls, specifically for situations like this where any of the sub-objects could be null?

OldType.SubType.AnotherSubType.SomeProperty
1

There are 1 answers

3
René Vogt On

Since C# 6 you can use the null-propagation/null-conditional operator:

var NewType = new
{
    NewTypeId = old.SubType?.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country?.Abbreviation ?? "",
    Customer = old.SubType?.Customer?.Name ?? ""
};

If you have a class like

public class Example
{
    public int Value {get; set;}
}

and an instance

Example sample = GetExample();

then this expression:

sample?.Value

returns a Nullable<int>. And that has the value of Value if sample was not null or has no value (is null) if sample was null.