Is there a conditional ternary operator in VB.NET?
Asked Answered
G

5

499

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?

Gamophyllous answered 23/2, 2009 at 3:17 Comment(1)
A ternary operator is any operator that takes three operands, much like a binary operator takes two and a unary operator takes one. The ?: operator is a specific example of a ternay operator, not the definition.Surfacetosurface
T
674

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)
Tribasic answered 23/2, 2009 at 3:46 Comment(5)
Prior to 2008 it was IIf, which worked almost identically to the If operator described in your link.Surfacetosurface
...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.Begun
what is it means ? If (condition,true-part,false-part). may i rite ?Finbar
I'm a huge C guy, but I find this syntax cleaner than the traditional ternary operator.Champaigne
Another important distinction: 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
A
85

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.

Albritton answered 23/2, 2009 at 4:25 Comment(7)
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 ...Tribasic
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.Albritton
Nice to categorize all VB programmers ;-) And there is also IsNot and OrElse to shortcut, so VB does indeed support Short Circuit Evaluation.Ketron
Iif is a regular method call and evaluates all parameters. It is not ternary. Se dotnetslackers.com/VB_NET/…Ryswick
As I stated, it is NOT a true operator, and vb6 doesn't support short circuit evaluation so it always evaluates all operations on line anyway.Albritton
Method IIf is a part of Microsoft.VisualBasic namespace, that is not compatible with other .NET languages. So better practice is use If() mehod.Eby
@Aave: the namespace certainly is compatible with other languages, this particular function has always been rather pointless, but that doesn’t mean everything in the namespace is po8ntless or can only be used with vb.Otter
P
28

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.

Priesthood answered 16/8, 2012 at 15:50 Comment(4)
Just for completeness, the better way to write that expression is Dim foo As Integer? = If( someTrueExpression, New Integer?, 2).Flynn
Note that this also happen with Option Strict On. The reason is that Nothing in VB.NET is equivalent to C#'s default(T) rather than to null.Lille
And for anyone puzzled by Integer? it means it's nullable - see https://mcmap.net/q/75326/-make-an-integer-nullBugle
For anyone getting stuck on implicit conversion for nullable types - see this answer as to why and this answer for a workaround which casts the argument before returning (CType(Nothing, DateTime?).Downatheel
J
4

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns the basic Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just a basic object anyway
  • If true-part or false-part aren't just scalars but function calls, always both values will be evaluated. So be careful, if one evaluation could lead to an exception, even when due to the condition it would never be the chosen part.

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.
  • If true-part or false-part aren't just scalars but function calls, only the chosen part will be evaluated.
Janeljanela answered 5/12, 2020 at 0:45 Comment(0)
T
0
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))
Tuesday answered 11/1, 2022 at 21:1 Comment(1)
My answer adds to the existing, it is not reflected in the accepted answer and can be simpler if this is the use case they are using it for. Unfortunately I don't have enough reputation to comment under that post to share my update.Tuesday

© 2022 - 2024 — McMap. All rights reserved.