Peter Kellner
Peter Kellner

Reputation: 15508

In c# resharper suggested "conditional access", what does null give me?

I use Resharper to help with language features and I have a DateTime field that is nullable. Resharper suggested this syntax:

 TodayDate = paidDate?.ToString("d"),

It looks like a standard expresson but I don't get one question mark. two question marks I get and colon I get.

An explanation would be appreciated. whathappens when paidDate is null?

Upvotes: 21

Views: 12531

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

?. is a new feature introduced in C# and it's called Null-conditional Operators. It evaluates method call only when paidDate is not null, and returns null instead.

It's pretty much equivalent to

TodayDate = paidDate == null ? null : paidDate.ToString("d");

If you try calling a method that returns value type after ?. it will make the whole thing return Nullable<T> of that value type, e.g.

var myValue = paidDate?.Day;

would make myValue be typed as Nullable<int>.

Upvotes: 35

Related Questions