What is the purpose of single question mark on the right side of assignment in expression with null-coalescing operator? Example:
var a = collection?.First()?.somePropA ?? new A();
What is the purpose of single question mark on the right side of assignment in expression with null-coalescing operator? Example:
var a = collection?.First()?.somePropA ?? new A();
The single quotation mark (?.
) is newly added in C# 6.0 and represents a null
check.
So, for example, the following code is the same;
var foo = bar?.bar2;
Or
var foo = null;
if (bar != null)
foo = bar.bar2;
else
foo = null;
However, both can still return null
. Therefore one can use the ??
check to assign a value if the result indeed is null
.
That being said, one can write the following code;
var foo = bar?.bar2 ?? new Bar2();
which is basically the same as
var foo = null;
if (bar != null)
foo = bar.bar2;
else
foo = new Bar2();
Using ?.
multiple times can really shorten your code. Consider, for example, the following line;
var foo = bar?.bar2?.bar3?.bar4?.bar5 ?? new Bar5();
this is syntactic sugar for
var foo = null;
if (bar != null)
{
if (bar.bar2 != null)
{
if (bar.bar2.bar3 != null)
{
if (bar.bar2.bar3.bar4 != null)
{
if (bar.bar2.bar3.bar4.bar5 != null)
foo = bar.bar2.bar3.bar4.bar5;
else
foo = new Bar5();
}
else
foo = new Bar5();
}
else
foo = new Bar5();
}
else
foo = new Bar5();
}
else
foo = new Bar5();
Of course, there are already way better ways to write the above (for example, by initializing foo = new Bar5()
before doing all the checks), but for clarity I kept it this way.
?.
is a new operator that helps a developer to omit excessive checks for null.
You can read more here: https://msdn.microsoft.com/en-us/library/dn986595.aspx
collection.First()
takes the first item from the collection. If that is not null
it will call somePropA
. If it is null
(here comes the purpose of this operator), it will return null
: it is just a smart way to do a null check. It is called the null-conditional operator.
That single character prevents the need for checking each and every property or return value for null
.
Another way to write this:
var a = ( collection != null && collection.First() != null
? collection.First().somePropA : null
) ?? new A();
Or:
A a;
if (collection != null && collection.First() != null)
{
a = collection.First().somePropA;
}
else
{
a = null;
}
if (a == null)
{
a = new A();
}