In VB.NET, I have to compare some objects within a select case statement.
Since select case uses = operator by default and this is not defined for objects, a compile error is thrown.
I presently use this workaround:
Select Case True
Case sender Is StyleBoldButton
Case sender Is StyleUnderButton
Case sender Is StyleItalicButton
End Select
which actually works.
Is there something prettier to see and more understandable?
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 useIs. (OrObject.Equals(objA As Object, objB As Object)– but, really, why? when you’ve gotIs?)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 Casedoesn’t doIs. (well, it does, but that’s a differentIs, more like theitof Hypercard.) I think the ladder looks smart and easy to follow:As you have pointed out, the
Select Case Truepattern 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:
Here I’m counting on
.Equalsto work like the C#==when faced with twoobjecttypes to compare (see http://visualstudiomagazine.com/articles/2011/02/01/equality-in-net.aspx). The beauty of this is thatsenderis mentioned only once; however there’s all thisElseIf .Equals( ... ) Thenyou’ll have to type for each “Case”.Another way I won’t use myself is using
GetHashCode():Here I’m counting on what (very) little I know of
GetHashCode()to uniquely (enough) identify these controls. (See Default implementation for Object.GetHashCode() ).