C# 2.0 introduced the ?? or null coalescing operator. The ?? operator has two operands and can be used in an expression as follows:

x = y ?? z;

The ?? operator returns the left-hand operand if the left-hand operand is not null, otherwise it returns the right-hand operand. In the example above, if ‘y’ is not null, then ‘x’ is set to ‘y’; however, if ‘y’ is null, then ‘x’ is set to ‘z’.

For example, assume we have a Form reference ‘oldForm’:

Form oldForm;

We want to set the ‘newForm’ reference to ‘oldForm’. Except if ‘oldForm’ is null, we want to create a new Form. This logic can be written using if-else as follows:

Form newForm = null;
if (oldForm != null)
    newForm = oldForm;
else
    newForm = new Form();

Which can be rewritten using the ternary ? operator as follows:

Form newForm = oldForm != null ? oldForm : new Form();

Which can be rewritten using the null coalescing ?? operator as follows:

Form newForm = oldForm ?? new Form();
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot