Simon
Simon

Reputation: 1476

Check for null before select on linq

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?

Upvotes: 4

Views: 8333

Answers (2)

Developer
Developer

Reputation: 6440

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.

Upvotes: 8

Paul Raff
Paul Raff

Reputation: 346

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.

Upvotes: 2

Related Questions