0

Is it possible to create a class in VB.NET that can be compared to a string in a switch statement? For example, let's say I have a class Foo:

Public Class Foo
    Public Bar As String = "test"
End Class

Is it possible to implement some interface or override some equality operator so that I could use Foo like so?

Dim foo As New Foo()

Select Case "test"
    Case foo
        ' It worked!
End Select
Kevin Pang
  • 41,172
  • 38
  • 121
  • 173

2 Answers2

4

Yes, you can define implicit conversion operators in the .NET languages that allow the compiler to implicitly convert an instance of your class to another type.

In VB.NET, this is called the "Widening" operator. You define it like this:

Public Class Foo
    Public Bar As String = "test"

    Public Shared Widening Operator CType(ByVal f As Foo) As String
        Return f.Bar
    End Operator
End Class

There is also explicit conversion, which is called the "Narrowing" operator in VB.NET. Just as it sounds, the former conversion can happen automatically, while the latter requires you to explicitly instruct the compiler to perform the conversion. This can prevent some nasty surprises, but also clutters the code.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • What if Bar were a List(Of String) instead and I wanted to define equality between my class and a string as simply: does Bar contain the string we're comparing against. Would that be doable? – Kevin Pang Jan 13 '12 at 01:20
  • @Kevin: Hmm, that's a different question. I would overload the equals operator. See [here](http://msdn.microsoft.com/en-us/library/336aedhh.aspx) for an example. Remember that when overloading `Equals`, you should [probably also overload `GetHashCode`](http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c). – Cody Gray - on strike Jan 13 '12 at 01:23
0

I think, based on your question, that you want to see if Bar in a given class instance is equal to test.

If so, you can leverage the ToString() override:

Public Class Foo
    Public Bar As String = "test"

    Public Overrides Function ToString() As String
        Return Bar
    End Function
End Class

and your case statement then becomes:

    Dim foo As New Foo()

    Select Case "test"
        Case foo.ToString
            ' It worked!
    End Select

You could also implement a default property, but that isn't as clean because a default property are required to have a parameter.

Public Class Foo
    Public Bar As String = "test"

    Default Public ReadOnly Property DefaultProp(JustUseZero As Integer) As String
        Get
            Return Bar
        End Get
    End Property
End Class

which would then be called as:

    Dim foo As New Foo()

    Select Case "test"
        Case foo(0)
            ' It worked!
    End Select
competent_tech
  • 44,465
  • 11
  • 90
  • 113