On Jul 15, 12:34*pm, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
Hi,
I have a class clsSubClass which inherits from clsClass.
When I instantiate an object of clsClass (MyClass), and I instantiate an
object from clsSubclass (MySubClass) I can do an "MyClass = MySubclass"..
But when I declare two generic list of them ("Dim MyList1 as List(Of
clsClass)" and "Dim MyList2 as List(Of clsSubClass)"), I can't do an
"MyList1 = MyList2".
Why is this exactly, and is there a way to implement this behaviour?
It has already been explained why it doesn't work like that, but there
are workarounds, depending on what exactly you're trying to do.
Typically, you don't want variance on variables - you want it on
function arguments. In this case, you can use generics yourself. For
example, say, you have a function that should take an arbitrary
IEnumerable(Of BaseClass). You could write it like that:
Public Sub PrintAll(items As IEnumerable(Of BaseClass)
For Each item In items ...
End Sub
But then you won't be able to pass IEnumerable(Of DerivedClass) to
this function. The workaround is to do this:
Public Sub PrintAll(Of TItem As BaseClass)(items As IEnumerable(Of
TItem))
For Each item In Items ...
End Sub
Now that the function is explicitly declared as taking IEnumerable of
_any_ TItem which inherits from BaseClass, it can take IEnumerable(Of
DerivedClass) just fine.
Unfortunately, this workaround is for covariance only; you cannot do
usage-site contravariance with it (e.g. write a method that works on
any IList(Of TItem) such that it would support method Add(BaseClass)).