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:
VB.NET,
.NET 3.5,
.NET