A True Ternary Operator for VB.net

I had a rather lengthy blog entry about a month ago where I talked about the lack of a ternary operator in VB.net.  You can read that entry here

Well, as it turns out, Paul Vick posted recently about new language features going into .Net 3.5 and it appears that a true ternary operator has been added to the list of features.  The syntax they chose, as it turns out, is rather easy.  I'll give an example below using my normal DataReader example.

In VB.net 2.0:

 Dim description As String
 If reader.IsDBNull(_indexDesc) Then
     description = Nothing
 Else
     description = _
      reader.GetString(_indexDesc).Trim()
 End If

In C# 2.0:

string description = reader.IsDBNull(_indexDesc) ? null : 
                              reader.GetString(_indexDesc).Trim();

And now, without further ado...

In VB.net 3.5:

Dim description as String =_
                If(reader.IsDBNull(_indexDesc), _
                     nothing, reader.GetString(_indexDesc).Trim())

As you can see, they are reusing an existing operator, but they're doing it in a way that makes sense - at least to me.  I don't see how else they would have done it without introducing some arcane symbols like in C#.

In any case, this makes me very happy as this has long been something that has bugged me about VB.  You can read about all of the other features being added to the next build of VB 2008 here.

 

Technorati Tags: , ,
Published 22 July 07 12:59 by Greg
Filed under: ,

Comments

# Todd Meinershagen said on July 22, 2007 10:45 AM:

Isn't this ternary operator a lot like the IIf() function where you have a expression and then a true part and false part?  I think using If and IIf for the same feature will be confusing to your average VB developer.

# Greg said on July 22, 2007 10:52 AM:

Hey Todd,

Actually the IIF is just a function and not a true language feature - and as such, it doesn't operate the same way that a true short-circuiting operator like this does.  I have a lengthy discussion on the problem at http://samuraiprogrammer.com/community/blogs/greg/archive/2007/06/22/IIF-in-VB.net-vs.-_3F00_-_3A00_-in-C_2300_.aspx

Anonymous comments are disabled