Click here to Skip to main content
13,552,926 members
Rate this:
Please Sign up or sign in to vote.
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?
Posted 13-Jun-12 5:58am
Updated 13-Jun-12 7:03am
SAKryukov 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

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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:
<pre lang="vb"">
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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04-2016 | 2.8.180515.1 | Last Updated 13 Jun 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100