Null-checking Null propagation operator (?.)

"Null propagation operator", translated as null conditional operator in "C# Essentials".

When calling a method with a null value, a System.NullReferenceException exception will be thrown at runtime, which usually indicates an error in program logic. Given the high frequency of this pattern of checking for null values ​​before calling members, C# 6.0 introduced a more simplified null-condition operator ?..

The null conditional operator checks whether the operand is null before calling the method or property, and if it is null, the method group is not executed.

 private bool IsOk(List<int> rooms)
 {
     return rooms.Count > 0;
 } 

When the above rooms are empty, an exception will be reported.

To do empty processing:

    private bool IsOk(List<int> rooms)
    {
        if (rooms != null)
        {
            return rooms.Count > 0;
        }

        return false;
    }

Use the "null-propagation operator" to simplify writing:

 private bool IsOk(List<int> rooms)
 {
     return rooms?.Count > 0;
 } 

Example 2:

A?.Invoke("Hehe");

The above example is equivalent to

if(A == null)
{
   //不执行
}
else
{
   A.Invoke("Hehe");
}

Guess you like

Origin blog.csdn.net/qq_42672770/article/details/123919257