tags:

views:

926

answers:

4

I seem to recall something about avoiding the Immediate If operator (?:) in C#, but I don't know where I read it and what it was. I think it had to do with the fact that both the true and the false part are executed before deciding on the outcome of the condition. Is this correct? Or is this so in VB.Net?

+19  A: 

It's actually called conditional operator and is referred to as "?:" in the MSDN. It is basically a shorthand notation for if-else except that this is actually expression, not statement. Since it's equivalent for if there are no caveats to this operator.

What you've read is about is possibly about Iif function in VB.NET. Being a function it evaluates all its arguments before being invoked, so

Dim s As String = Iif(person Is Nothing, String.Empty, person.FirstName)

will result in NullReferenceException being thrown.

Anton Gogolev
Good catch, Anton! Gerrie probably did read about the IIf function in VB.
Cerebrus
Yes I was probably mistaking with the VB.Net IIf function. Thanks.
Gerrie Schenck
The IIF function (that exists way back in Access 2 Basic and early VBA) is bad for the previously mentioned reasons. VB .NET as of .NET 3.5 now has an IF operator, syntax wise it looks like IIF but it behaves like ?:
pipTheGeek
Though MSDN does call it the conditional operator, I think most of us refer to it as the ternary operator - owing to the 3 args it takes. Iif() is usually called Inline If...and I'm not sure what folks call the new VB9 If operator - besides VB's ternary operator....
Mark Brackett
+1  A: 

Futher to Anton's reply- note that this is also the only way to specify this type of thing in a lambda expression (for LINQ-to-[some db] etc).

The downside is that if you are testing multiple things, it can get confusing. See the discussion here for an example covering type-testing with/without predicates.

Marc Gravell
+1  A: 

The main downside i see in using ?: instead of a "regular" if-else block is about readability and maintainability; most critics argue that if-else is clearer than ?:, even if i think this is about personal taste, but it's plain to see that if you need to add an instruction to a ?: statement in any of the branches you need to completely rewrite it using if-else, thus making if-else a better choice from the beginning.

Raibaz
return error == ERR_REOF ? "End of File" : error == ERR_NOMEM ? "Out of memory" : error == ERR_NOTFOUNT ? "File not found" : "Unknown error";Perfectly readable use of my favourite nested operator.
Steve Hanov
like i said, "readable" is subjective :)
Raibaz
+1  A: 

Only use it for simple things like

Console.WriteLine(MyBool ? "It's true!" : "Nope");

If you try to add logic to the inside, then the code looks really bad.

GeekyMonkey