Anything that has the requisite comparison operators (=, >=, <=, etc.) defined is fair game for Select Case
. Rightly (or wrongly), references just aren't compared with =
in VB; one must use Is
. (Or Object.Equals(objA As Object, objB As Object)
- but, really, why? when you've got Is
?)
But take a look at Object equality behaves different in .NET - perhaps the VB way is less confusing? Whatever, I think you're stuck with the If-ElseIf ladder since Select Case
doesn't do Is
. (well, it does, but that's a different Is
, more like the it
of Hypercard.) I think the ladder looks smart and easy to follow:
If sender Is StyleBoldButton Then
ElseIf sender Is StyleUnderButton Then
ElseIf sender Is StyleItalicButton Then
Else
End If
As you have pointed out, the Select Case True
pattern is an "OrElse" short-circuit workaround in VB6 - a wonky way to meet a real need. But that's not needed in VB.NET. In that spirit, maybe it's better to use design patterns more in line with the best practices expected of an object-oriented language. For example, as Denis Troller suggested, why not give each button its own event handler?
But if you insist on something like an Is-able Select, here's something I probably won't use myself:
With sender
If .Equals(StyleBoldButton) Then
ElseIf .Equals(StyleUnderButton) Then
ElseIf .Equals(StyleItalicButton) Then
Else
End If
End With
Here I'm counting on .Equals
to work like the C# ==
when faced with two object
types to compare (see http://visualstudiomagazine.com/articles/2011/02/01/equality-in-net.aspx). The beauty of this is that sender
is mentioned only once; however there's all this ElseIf .Equals( ... ) Then
you'll have to type for each "Case".
Another way I won't use myself is using GetHashCode()
:
Select Case sender.GetHashCode()
Case StyleBoldButton.GetHashCode()
Case StyleUnderButton.GetHashCode()
Case StyleItalicButton.GetHashCode()
Case Else
End Select
Here I'm counting on what (very) little I know of GetHashCode()
to uniquely (enough) identify these controls. (See Default implementation for Object.GetHashCode() ).