Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for null before select on linq

Tags:

c#

.net

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?

like image 541
Simon Avatar asked Sep 06 '25 03:09

Simon


2 Answers

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.

like image 80
Developer Avatar answered Sep 07 '25 23:09

Developer


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.

like image 26
Paul Raff Avatar answered Sep 07 '25 23:09

Paul Raff