Tim Schmelter
Tim Schmelter

Reputation: 460028

Define a variable of different types

i wonder if it's possible to define a variable/property of more than one type.

Let's say i want a property TextWebControl that is a WebControl and also implements Web.UI.ITextControl(f.e. like a TextBox or Label). But i don't want to enforce that it is a TextBox or Label, but only one that inherits from WebControl and also implements ITextControl so that it also would work with controls added in future releases of .Net-Framework.

Edit: I have retagged the question and added VB.Net because it's my default language. Normally it's no problem for me to understand C# also, but i must admit that it's difficult to translate generic stuff to VB.Net without experiences and it's also better documentated in C# than in VB. So i would appreciate(and aceept) a working example of a VB.net generic type of ITextControl/WebControl.

From Marc's answer i understand that i need a generic class. But how do i instantiate it in SomeClass? This won't compile:

Class SomeClass
   Public Property info As InfoControl(Of WebControl, ITextControl)
End Class

Public Class InfoControl(Of T As {WebControl, ITextControl})
End Class

Thank you very much.

Upvotes: 1

Views: 363

Answers (3)

Chris Haas
Chris Haas

Reputation: 55417

Here's the VB version of a generic class with multiple constraints:

Public Class SomeClass(Of T As {WebControl, ITextControl})
    Private _item As T
    Public Property Item() As T
        Get
            Return Me._item
        End Get
        Set(ByVal value As T)
            Me.ParseValue(value)
            Me._item = value
        End Set
    End Property
    Public Sub ParseValue(ByVal value As T)
        ''//do something with value here if you want
    End Sub
    Public Sub New(ByVal item As T)
        Me._item = item
    End Sub
End Class

And to instantiate it you'd do this:

    Dim L As New Label()
    Dim S1 As New SomeClass(Of Label)(L)

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44595

I would say either you define your variable of a certain interface, or you use the lowest possible base class derived by all classes you think you would need to support.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062510

Only inside generics, i.e.

void SomeMethod<T>(T whatever) where T : WebControl, ITextControl {...}

Otherwise, you are going to have to pick between them, or have 2 variables.

Upvotes: 4

Related Questions