2

is it possible to extend different classes with the same generic class? I tried something like this:

Public Class A
  Public Sub TestA()
    Debug.Print("Test A")
  End Sub
End Class

Public Class B(Of T)
  Public Sub TestB()
    Debug.Print("Test B")
  End Sub
End Class

Public Class C
  Inherits B(Of A)

  Public Sub TestC()
    TestA() '**<-- Thows error 'is not declared'** 
    TestB()
    Debug.Print("Test C")
  End Sub
End Class

I basicly have some usercontrols, which derive from Combobox or Textbox and i'd like both to implement some functions(and interfaces) that are defined in a base class. In C++ i'd do it with multi inheritance.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
rene marxis
  • 385
  • 2
  • 13
  • 1
    You may want to look into "mixins" http://stackoverflow.com/questions/6644668/mixins-with-c-sharp-4-0 – Derek Sep 12 '13 at 10:59

3 Answers3

4

is it possible to extend different classes with the same generic class?

Generics isn't some kind of "workaround" for a lack of multiple inheritance, no. Your class C doesn't derive from A - it just means that the T in B(Of T) would be A in the context of C.

Which instance of A would you expect TestA() to be called on? Creating an instance of C certainly doesn't create an instance of A...

The fact that B(Of T) doesn't use T anywhere should be a warning signal - types which are generic but never use their generic type parameters are generally problematic.

It's hard to know exactly how to help you solve your real problem without more details, but you can't add a common base class in like this, when you also need to derive from other types which aren't under your control.

Perhaps extension methods would help?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You could make both your Combobox and your Textbox classes implement the same interface.

Then you could define extension methods on that interface class.

Derek
  • 7,615
  • 5
  • 33
  • 58
0

Thanks to your hint i got this working with extentions

Public Class Form1

    Public Interface IA
        Property val As String
    End Interface

    Public Class A
        Public Sub test()
            Debug.Print("test")
        End Sub
    End Class

    Public Class C
        Inherits A
        Implements IA

        Public Property val As String Implements IA.val

        Public Sub TestC()
            val = "testxxx"
            TestA()        
            test()
        End Sub
    End Class

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim ct As New C
        ct.TestC()
    End Sub
End Class

Module TestModule
    <Extension()>
    Public Sub TestA(ByVal pvIA As IA)
        Debug.Print(pvIA.val)
    End Sub
End Module

This way every class can implement it's own 'parent' (like A here) and i don't need to implement the function TestA for every class.

thank you

rene marxis
  • 385
  • 2
  • 13