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();
				
                        
                            
                        
                        
                            On
                            
                                                    
                    
                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();
}
                        
                        
                            
                        
                        
                            On
                            
                                                    
                    
                ?. 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
The single quotation mark (
?.) is newly added in C# 6.0 and represents anullcheck.So, for example, the following code is the same;
Or
However, both can still return
null. Therefore one can use the??check to assign a value if the result indeed isnull.That being said, one can write the following code;
which is basically the same as
Using
?.multiple times can really shorten your code. Consider, for example, the following line;this is syntactic sugar for
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.