Home » Development » These two operators can make your life easier: null-coalescing and ternary operators

These two operators can make your life easier: null-coalescing and ternary operators

Null-coalescing operator (??)

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
myNewValue = myValue ?? "other value";

Ternary operator (?:)

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
condition ? first_expression : second_expression;
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result.
classify = (input > 0) ? "positive" : "negative";

Source: https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment