new test { return new test{ obj1 = "", obj2 = "", }I have not see" />

Check for null before select on linq

c# .net linq

2079 просмотра

2 ответа

I have just installed ReSharper, and it has altered

if(dto != null)
{
    return new test{
     obj1 = "",
     obj2 = "",
 }
}

into

 return dto?.Select(item => new test
      {
    return new test{
     obj1 = "",
     obj2 = "",
 }

I have not seen before

dto?.Select

tried to google the meaning with no luck.. could someone please explain , or point me in the right direction to the deffination

I gather its simply checking for null?

Автор: Simon Источник Размещён: 08.11.2019 11:22

Ответы (2)


4 плюса

Решение

Null propagation operator is newly introduced in C# 6. return dto?.Select... means, if dto is null then this statement will return null else will execute the remaining part. Another example, just making it up, assume you have Employee object with Address property which inturn has Lane (string), Pincode etc. So if you need to get the address lane value you could do:

var lane = employee?.Address?.Lane;

Which will return null if employee or address is null; otherwise returns lane value.

This could be combined in many ways and is really handy. For eg,

int someIntegerValue = someObject?.SomeIntValue ?? 0;

Basically you could avoid many null checks with this feature.

Автор: Developer Размещён: 20.08.2016 01:46

1 плюс

The question-mark operator acts on nullable values and

x?<operation>

translates to

x.HasValue ? x.Value.<operation> : null

It's basically saying "do this if I'm not null; otherwise keep me as null".

Do you have a

return null

statement later in your original code? I am surprised ReSharper would assume a return null in its transformation.

Автор: Paul Raff Размещён: 20.08.2016 01:44
32x32