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?
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 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)
Iif
always returns an object of type Object
, whereas If(bool, obj, obj)
allows for type-checking with option strict on. (Dim var As Integer = Iif(true, 1, 2)
won't compile with option strict on because you could just as easily write Dim var As Integer = Iif(true, new Object(), new Object())
. You CAN write Dim var As Integer = If(true, 1, 2)
with option strict on though, because it'll check the type returned.) –
Unseen 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 you're 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.
Dim foo As Integer? = If( someTrueExpression, New Integer?, 2)
. –
Flynn Option Strict On
. The reason is that Nothing
in VB.NET is equivalent to C#'s default(T)
rather than to null
. –
Lille Integer?
it means it's nullable - see https://mcmap.net/q/75326/-make-an-integer-null –
Bugle CType(Nothing, DateTime?
). –
Downatheel Just for the record, here is the difference between If and IIf:
IIf(condition, true-part, false-part):
If(condition, true-part, false-part):
If(<expression>, <expressionIfNothing>)
If <expression>
evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns <expressionIfNothing>
(Intellisense)
This is useful for checking that a particular value exists, and if not replacing it.
Example:
If(cat, dog)
Here, if the cat is not null, it will return cat. If it is null, it will return dog. Most of the time you will be using a ternary operator for this scenario. However, if you do not want to return the value you are testing you will have to use this instead:
If(condition, cat(true), dog(false))
© 2022 - 2024 — McMap. All rights reserved.