Null-coalescing and Ternary operator in C#

There is a smarter way of avoiding null values in string assignment. Many of us use ternary operator, Format etc. to handle null value like below-

  1. string studentHobbies = (txtHobbies.Text != null)  ? txtHobbies.Text : string.Empty;

The same statement can be written using null-coalescing operator (??) in following manner -

  1. string studentHobbies = txtHobbies.Text ?? string.Empty;

The above statement is the same as the preceding example statement.?? evaluates the first operand against null and -

  • If txtHobbies is null then right operand is returned
  • If txtHobbies is not null then left operand is returned

Below are the important points regarding Null-coalescing-

  • Null coalescing operator can be used with Reference types and nullable types.
  • Null coalescing is a binary operator which is used for conditional assignment by checking the null.
  • Null coalescing is a right associative operator like assignment and other conditional operators. So, its priorities the evaluation from right to left.