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
Since C# 6 you can use the null-propagation/null-conditional operator:
If you have a class like
and an instance
then this expression:
returns a
Nullable<int>. And that has the value ofValueifsamplewas notnullor has no value (isnull) ifsamplewasnull.