Is there a conditional ternary operator in VB.NET?

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?


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

Example:

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

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.


If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

For example, if your not careful you may be tempted to try something like:

Dim foo As Integer? = If( someTrueExpression, Nothing, 2)

Will give "foo" a value of 0!

I think the '?' operator equivalent in C# would instead fail compilation

链接地址: http://www.djcxy.com/p/1140.html

上一篇: Haskell的规模设计?

下一篇: VB.NET中是否有条件的三元运算符?