I found this article on the webs and thought I’d try to apply the null string style method to my excel range value. Sometimes it has a value in it and sometimes it doesn’t and obviously double doesn’t like null values.
This is my little snippet.
double valTotal = (rngTotal.Value != null ? 1 : 0);
My question is what am I doing with this above code? It looks like an if statement in one line with the “1” being the “then” and the “0” being the “else”. Is that right? And most importantly, what is the name of this syntax so I can find out more about this?
It’s the conditional operator. (Sometimes incorrectly called the ternary operator; it’s a ternary operator as it has three operands, but its name is the conditional operator. If another ternary operator is ever added to C#, “the ternary operator” will become an ambiguous/non-sensical phrase.)
Quick description:
The first operand is evaluated, and if the result is
true, the second operand is evaluated and forms the overall value of the expression. Otherwise the third operand is evaluated and forms the overall value of the expression.There’s a little more detail to it in terms of type conversions etc, but that’s the basic gist.
Importantly, the first operand is always evaluated exactly once, and only one of the second or third operand is evaluated. So for example, this is always safe:
That can never throw a
NullReferenceExceptionastext.Lengthisn’t evaluated iftext == nullis true.It’s also important that it’s a single expression – that means you can use it in some places (such as variable initializers) where you couldn’t use the if/else equivalent.
Closely related is the null-coalescing operator which is also worth knowing about.