views:

4611

answers:

2

In Perl (and other languages) a conditional ternary operator can be expressed like this:

my $foo = $bar = $buz ? $cat : $dog;

Is there a similar operator in VB.NET?


Thanks to Lucky and Kris, I now know that in VB.NET this operation is expressed like this:

Dim foo as String = IF(bar = buz, cat, dog)
+11  A: 

Depends. The If operator in VB.NET 2008 acts as a ternary operator. This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Jess
Prior to 2008 it was IIf, which worked almost identically to the If operator described in your link.
Zooba
...with the important difference that Iif(), being a function, always evaluated both the consequent and the alternative, while the new If only evaluates one of them.
Greg Hewgill
+6  A: 

iif has always been available in VB, even in VB6.

Dim foo as String = iif(bar = buz, cat, dog)

It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.

Kris Erickson
Iif is only close to a ternary operator though - which means you couldn't use it in every condition that you would an If Then Else (or ternary operator). For example, Value = Iif(1 = 1, 0, 1/0) would blow up, but Value = If(1 = 1, 0, 1/0) would not ...
Jess
VB doesn't support Short Circuit evaluation (except for the AndAlso operator), so VB programmers don't really expect that they can safely evaluate half an operation. But point taken, also iif is a hack function that was put in for backward compatibility otherwise it would be a real operator.
Kris Erickson
Nice to categorize all VB programmers ;-) And there is also IsNot and OrElse to shortcut, so VB does indeed support Short Circuit Evaluation.
HardCode