Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: .NET3.5 VB.NET Generics
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 6:58am
Edited 13-Jun-12 8:03am
VJ Reddy38.6K
v3
Comments
SAKryukov at 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 at 13-Jun-12 13:03pm
   
Edit: pre tags for VB.NET code added

1 solution

Rate this: bad
good
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
            Me.Add(Item)
        Next
    End Sub
End Class
and then in your code:
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.
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 269
1 OriginalGriff 240
2 CPallini 195
3 Maciej Los 177
4 BillWoodruff 173
0 OriginalGriff 5,655
1 DamithSL 4,506
2 Maciej Los 3,997
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,180


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 13 Jun 2012
Copyright © CodeProject, 1999-2014
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