C#'s Null-Coalescing (??) Operator

Although I've always been a big fan of the ternary operator, kudos goes to the Refactoriser (you know who you are!) for pointing me in the direction of an even more effective way of obfsuca^H^H^H tidying up my code; the ?? operator.

The null-coalescing operator (to call it by its more catchy name) allows you to provide an alternative value in the event that the reference type object (or nullable value type) you are trying to access evaluates to null. So instead of having to do something like this:

            int? myNullableInt = null;
            int myInt;

            if (myNullableInt == null)
                myInt = -1;
                myInt = (int)myNullableInt;

You can do this in-line:

myInt = myNullableInt ?? -1;

Apologies for the heavily contrived and quite pointless example, but at least it gets the syntax down and should make it apparent how useful this operator can be when dealing with a mixture of nullable and non-nullable types.

Share this: