Craig Norton
Craig Norton

Reputation: 1047

Create Generic List from a subclass

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?

Upvotes: 0

Views: 1680

Answers (3)

Oliver Hallam
Oliver Hallam

Reputation: 4262

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

Upvotes: 0

Oliver Hallam
Oliver Hallam

Reputation: 4262

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

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 100047

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

Upvotes: 1

Related Questions