Easy way to do C # Null validation in type conversion

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

They look something like 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 that I convert are usually Entity Framework objects. I also do not have the ability to change the classes that I will convert.

Is there an easier way to check for zeros, in particular for situations like this, when any of the sub-objects can be null?

OldType.SubType.AnotherSubType.SomeProperty
+4
source share
1 answer

Starting in C # 6, you can use the zero / conditional zero distribution 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 instance

Example sample = GetExample();

:

sample?.Value

Nullable<int>. Value sample null ( null), sample null.

+3

Source: https://habr.com/ru/post/1665022/


All Articles