Coalesce and Ternary Operators
Posted
Tue, Jul 28 2009 13:12
by
Deborah Kurata
Coalesce Operator
The coalesce operator, also called the null coalescing operator, is new in VB 9 and C# 2.0. It helps you work with nulls (Nothing in VB).
The coalesce operator involves two expressions. The first expression must evaluate to a nullable type or reference type. The first expression is the result if the first expression evaluates to a non-null value. The second expression is the result if the first expression evaluates to null (Nothing in VB).
In C#:
string result = value ?? "<Empty>";
?? is the coalesce operator in C#. It is of the general form:
Exression ?? NullResult
In VB:
Dim result As String = If(value, "<Empty>")
The If keyword is used as the coalesce operator in VB. It is of the general form:
If(Expression ?? NullResult)
To use the coalesce operator, the value variable in the above examples must be a nullable type or a reference type. If value is non-null, value is returned. If value is null (Nothing in VB), the second parameter is returned. Here are some examples:
- value = “CA” result = “CA”
- value = String.Empty result = String.Empty
- value = null (nothing in VB) result = “<Empty>”
Use the coalesce operator any time you need to have special case handling of a null.
Ternary Operator
The ternary operator, also called the conditional operator, is new in VB 9 and has been in C# from the beginning. For a general description of a ternary operator, see this.
The ternary operator involves three expressions (hence the name ternary). The first expression is a Boolean expression that evaluates to true or false. The second expression is the result if the first expression is true. The third expression is the result if the first expression is false.
In C#:
string result = value == null ? "<Empty>" : "<Full>";
? is the ternary operator in C#. It is of the general form:
Condition ? TrueResult : FalseResult
In VB:
Dim result As String = If(value Is Nothing, "<Empty>", "<Full>")
The If keyword is used as the ternary operator in VB. It is of the general form:
If(Condition, TrueResult, FalseResult)
NOTE: In VB, you should always favor the ternary If() syntax over the old IIF syntax, which was inefficient and not recommended for use.
In the examples, if first expression is true, the second expression is returned. If the first expression is false, the third expression is returned. Here are some examples:
- value = “CA” result = “<Full>”
- value = String.Empty result = “<Full>”
- value = null (nothing in VB) result = “<Empty>”
Use the ternary operator any time you need two different results depending on a Boolean expression.
Enjoy!