mardi 27 décembre 2016

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

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





Aucun commentaire:

Enregistrer un commentaire