Alexis B.
Alexis B.

Reputation: 166

Null coalescing operator with the variable itself

Is there any way of reduce the null coalescing operator expression when the variable we check is the one we will assign if it's not null?

Example:

DateTime? date1 = DateTime.Parse("11/05/1990");
DateTime? date2 = DateTime.Now;
date1 = date1 ?? date2;

For instance, something like that:

date1 = ?? date2;

I know that's not a big deal but I'm curious.

Upvotes: 2

Views: 708

Answers (3)

Alfred Luu
Alfred Luu

Reputation: 2026

Starting from C# 8.0, the null-coalescing assignment operator, ??=, is available.

So it would be

date1 ??= date2;

Upvotes: 0

Jon Hanna
Jon Hanna

Reputation: 113352

No. If there was then:

_field ?? (_field = CalculateFieldValue());

wouldn't be so common in memoised properties.

Upvotes: 2

Roy Dictus
Roy Dictus

Reputation: 33149

No, this does not exist in C#.

You can find the list of operators in https://msdn.microsoft.com/nl-nl/library/6a71f45d.aspx.

But isn't date1 = date1 ?? date2 short enough already ?

Upvotes: 4

Related Questions