Null-Conditional Operators

One of the most repetitive tasks you do as a programmer is to check a value for null before you work with it. The code to do this checking is typically all over your application. For example, the following verifies whether properties on an object are null before working with them. (For a more complete discussion of all operators, see the section “Understanding Operators” later in this chapter.)

C#

public bool IsValid()
{
    if (this.Name != null &&
        this.Name.Length > 0 &&
        this.EmpId != null &&
        this.EmpId.Length > 0)
    {
        return true;
    }
        else
    {
        return false;
    }
}

VB

Public Function IsValid() As Boolean
    If Me.Name IsNot Nothing AndAlso
        Me.Name.Length > 0 AndAlso
        Me.EmpId IsNot Nothing AndAlso
        Me.EmpId.Length > 0 Then

        Return True

    Else
        Return False
    End If
End Function

Both C# 6.0 and VB 14 now allow automatic null checking using the question mark dot operator (?.). This operator tells the compiler to check the information that precedes the operator for null. If a null is found in an If statement for example, the entire check is considered false (without additional items being checked). If no null is found, then do the work of the dot (.) to check the value. The code from earlier can now be written as follows:

C#

public bool IsValid()
{
    if (this.Name?.Length > 0 &&
        this.EmpId?.Length > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

VB

Public Function IsValid2() As Boolean
    If Me.Name?.Length > 0 AndAlso
        Me.EmpId?.Length > 0 Then

        Return True

    Else
        Return False
    End If
End Function


Note

The ?. operator is referred to as the Elvis operator because you can see two dots for the eyes and the question mark as a swoop of hair.


The null-conditional operator cleans up code in other ways. For instance, when you trigger events, you are forced to copy the variable and check for null. This can now be written as a single line. The following code shows both the old way and the new way of writing code to trigger events in C#.

C#

//trigger event, old model
{
  var onSave = OnSave;
  if (onSave != null)
  {
    onSave(this, args);
  }
}

//trigger event using null-conditional operator
{
  OnSave?.Invoke(this, args);
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset