#214 – Using the Null-Coalescing (??) Operator with Reference Types

The ?? operator is often used with nullable value types, assigning a value to an equivalent non-nullable type (e.g. int? to int).  But it can also be used with reference types.

The behavior with reference types is the same as with value types–the value of the expression is equal to the first operand, if non-null, or the second operand if the first operand is null.

Here’s an example:

            Person favArtist = new Person("Connee", "Boswell");
            Person oldBlueEyes = new Person("Frank", "Sinatra");

            Person buyCDOf = favArtist ?? oldBlueEyes;  // Frank is our fallback

In this example, buyCDOf will be assigned the Connee Boswell Person object.  But if the favArtist variable had been null, we would have defaulted to assigning buyCDOf to Frank Sinatra.