Friday, August 31, 2007 12:00 AM bart

Visual Basic 9.0 Feature Focus - The If Ternary Operator

Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover the If Ternary Operator, which is a true ternary operator, something that Visual Basic has been lacking in previous releases (contrast to C-based languages' ?: operator). If there's one thing I'm sure of, it's that you - as a seasoned VB developer - have already heard of (and been using) the Iif 'function' which is known as 'Immediate IF' (official KB source):

Dim i As Integer = 123
Dim sign As Integer = IIf(i < 0, -1, 1)

In the sample above, sign will be assigned the value '1' because i < 0 evaluates to false. If the condition would evaluate to true, the second parameter '-1' would become the output result. So what's wrong with this? Nothing but the color of Iif... I'm not kidding: the problem is in the color. Iif is not a built-in function but a regular function from some library, and therefore the Iif call is like a regular function call. Function calls cause all of the arguments to be evaluated in Visual Basic. Take a look at the following and try to predict the outcome:

Sub Main()
    Dim i As Integer = 123
    Dim sign As Integer = IIf(i < 0, Negative(), Positive())
    Console.WriteLine(sign)
End Sub

Function Negative() As Integer
    Throw New Exception("Oops!")
    Return -1
End Function

Function Positive() As Integer
    Return 1
End Function

Even though we're not interested in the Negative function call, it will still happen because all arguments to Iif need to be evaluated prior to calling Iif:

image

So, if you ever read the Iif is equivalent to the following, forget about it:

Sub Main()
    Dim i As Integer = 123
    Dim sign As Integer
    If
i < 0 Then
        sign = Negative()
    Else
        sign = Positive()
    End If
    Console.WriteLine(sign)
End Sub

Instead this is what a real ternary operator should be equivalent to. Luckily we have one now in VB 9.0, and guess what: it's denoted as If too, just like its If-statement counterpart:

Sub Main()
    Dim i As Integer = 123
    Dim sign As Integer = If(i < 0, Negative(), Positive())
    Console.WriteLine(sign)
End Sub

Function Negative() As Integer
    Throw New Exception("Oops!")
    Return -1
End Function

Function Positive() As Integer
    Return 1
End Function

Trimmed of the I from IIf: color fixed and no side-effect anymore :-). But there's more to the ternary operator in Visual Basic: if it's used with only two arguments it acts as a null-coalescing operator, just as the ?? operator in C# (which was introduced in v2.0). This is especially useful if you're working with Nullable Types:

Dim name As String = Nothing
Dim nameValue = If(name, "Not set") 'will be "Not set"

name = "Bart"
nameValue = If(name, "Not set") 'will be "Bart"

Basically this use of the If operator is equivalent to:

nameValue = If(name IsNot Nothing, name, "Not set")

It works with everything that can be null, including Nullable Types:

Dim age As Integer? = Nothing
Dim ageValue = If(age, -1) 'will be -1

age = 24
age = If(age, -1) 'will be 24

Notice that the If operator requires its result operandi to be of "compatible types" so that the result type can be inferred:

image

Null coalescing proves useful if you need to switch from something nullable to something which isn't nullable but supports some kind of "default value" or "missing value".

Happy coding!

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# 4 Links Today (2007-09-01)

Saturday, September 01, 2007 8:20 AM by 4 Links Today (2007-09-01)

Pingback from  4 Links Today (2007-09-01)

# VB 9.0 Feature Focus

Wednesday, September 05, 2007 6:50 PM by Nick's .NET Travels

In my previous post I commented that VB is coming of age in Visual Studio 2008 with better support for

# New Features of Visual Basic 9 Article Series

Thursday, September 27, 2007 5:47 AM by Walter Stiers - Academic Relations Team (BeLux)

In a series of 15 posts, Bart De Smet explores several of the new features in Visual Basic 9 . These

# Foundations of Functional Programming - Part 1

Sunday, January 27, 2008 5:29 PM by B# .NET Blog

Welcome back to this blogging series on functional programming. After some scene-setting in the previous

# A functional C# (type)switch

Thursday, April 10, 2008 9:17 PM by SZW

使用匿名函数扩展C#中的Switch

# A functional C# (type)switch

Thursday, April 10, 2008 9:17 PM by SZW

使用Lambda表达式扩展C#中的Switch

# Pattern Matching in C# - Part 8

Wednesday, April 16, 2008 2:27 AM by B# .NET Blog

In the last handful of posts in this series we&#39;ve been looking at ways to match a whole set of patterns

# VB 9.0 Feature Focus – Link Collection

Saturday, August 09, 2008 7:17 AM by B# .NET Blog

Collecting a few of my posts for easy quick reference: Visual Basic 9.0 Feature Focus – Introduction