0
Option Explicit On
Option Strict On

Public Class Class1

    Dim l As List(Of A)

    Public Sub New()
        l = New List(Of B)
    End Sub

End Class

Public Class A
End Class

Public Class B
    Inherits A
End Class<p>

I've run into this problem.
I have a list declared of a Generic Type 'A'
I want to define the list as a Generic Type 'B', which is a subclass of 'A'.

Why can't this be done, and how can the same effect be achieved?

Craig Norton
  • 1,047
  • 1
  • 10
  • 23

3 Answers3

1

It's a matter of variance, which C# doesn't support for generics. See Rick Byer's post on the subject.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
0

If you could cast a list of As as a list of Bs, then what would happen if you added an A?

Oliver Hallam
  • 4,242
  • 1
  • 24
  • 30
  • If the class A was used as the Generic type then it should act as an interface for any subclasses added. You should be able to use any methods / variables in A and B, and B if you explicitly cast it. – Craig Norton Oct 07 '08 at 21:18
  • Though obviously not, I'll think on the problem. – Craig Norton Oct 07 '08 at 21:28
0

In C# 4.0 (as announced yesterday) we are half way there.

Oliver Hallam
  • 4,242
  • 1
  • 24
  • 30