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();
It is +1 point which do I don’t like C# and I prefer VB.
There are already: != ? ;
I don’t like C# but I like your blog ;))
Thanks for explanation.
I like this operator because it shortens code a little bit.
I like it too, it’s elegant
that’s why i love C#