Click here to Skip to main content
15,881,689 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:
VB
public class Appointment
    inherits businessObjectBase

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

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

why cant i do the following:
VB
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?
Posted
Updated 13-Jun-12 7:03am
v3
Comments
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.
--SA
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:
VB
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
            Me.Add(Item)
        Next
    End Sub
End Class

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


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