Click here to Skip to main content
15,616,520 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
Here is my situation. I have a BusinessObjectBase class. I have my business objects defined as:
public class Appointment
    inherits businessObjectBase

Then I made a base collection class defined as
Public Class BusinessObjectCollectionBase(of T as {BusinessObjectBase})
   inherits bindinglist(of T)

I then define my specific collection classes as
Public Class AppointmentCollection
    inherits businessObjectCollectionBase(of Appointment)

why cant i do the following:
Dim Appcoll as AppointmentCollection
    Dim Coll as businessObjectCollectionBase(of BusinessObjectBase) = Appcoll

i can define an object as a businessObjectBase and set it to an Appointment Object without any problems, but what i would think would be essentially the same thing for the collection is not allowed. Am i just totally going about this the wrong way, or is there a way to work around this?
Updated 13-Jun-12 7:03am
Sergey Alexandrovich Kryukov 13-Jun-12 12:33pm    
This is a good question on the well-known problem of covariance/contraviariance for generics, my 5. To start with, read about these terms applied to generics. These feature depend on the version. Please tag your version of tagged .NET Framework and the language.
VJ Reddy 13-Jun-12 13:03pm    
Edit: pre tags for VB.NET code added

1 solution

Yeah, you can't do that. I know, it sucks.

The easy way to work around is to throw in a AddRange method to your BusinessObjectCollectionBase:
Public Class BusinessObjectCollectionbase(Of T As BusinessObjectBase)
    Inherits BindingList(Of T)

    Public Sub AddRange(values As IEnumerable(Of T))
        For Each Item As T In values
    End Sub
End Class

and then in your code:
Dim appointments As New AppointmentCollection
Dim businessBases As New BusinessObjectCollectionbase(Of BusinessObjectBase)

Viola! Both collections now hold references to the same objects but as differing types.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900