#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: