Is there a conditional ternary operator in VB.NET?

Jim Counts picture Jim Counts · Feb 23, 2009 · Viewed 226.3k times · Source

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?

Answer

Beep beep picture Beep beep · Feb 23, 2009

Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

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

[EDIT]

Prior to 2008 it was IIf, which worked almost identically to the If operator described Above.

Example:

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