473,399 Members | 3,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

List(Of clsClass) = List(Of clsSubClass)

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?
Thanks a lot in advance,
Pieter
Jul 15 '08 #1
11 981
"Pieter" <pi****************@hotmail.comwrote:
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?
You can't do that because it would allow you to add superclass instances to
a list that, by its definition, is only supposed to contain subclass
instances.

Of course, you can write a loop to copy the elements to a separate list of
another type.

Eq.
Jul 15 '08 #2
On Jul 15, 9:34*am, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
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".
Indeed. That's because generics don't exhibit variance.
Why is this exactly, and is there a way to implement this behaviour?
Brief answer: consider this code.
List<BananabananaBunch = new List<Banana>();
List<Fruitfruitbowl = bananaBunch;
fruitbowl.Add(new Apple());

Suppose this were legal - then bananaBunch would contain an Apple,
which is clearly invalid.

For a lot of detail, see Eric Lippert's series of blog articles:
http://blogs.msdn.com/ericlippert/ar...e/default.aspx

Jon
Jul 15 '08 #3
Oh yes indeed you're right :-S I should have thought about that :-)

Although: An Import doesn't work neither, which should work in my opnion?
Because clsSubClass is also an clsClass: it shoudl be able to import these
items...
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:e6**********************************@l64g2000 hse.googlegroups.com...
On Jul 15, 9:34 am, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
Jul 15 '08 #4
On Jul 15, 9:55*am, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
Oh yes indeed you're right :-S I should have thought about that :-)

Although: An Import doesn't work neither, which should work in my opnion?
Because clsSubClass is also an clsClass: it shoudl be able to import these
items...
What exactly would you expect an import to do? You just can't treat a
list of bananas as if it's a general list of fruit. You can create a
new list of fruit and copy the contents of a list of bananas into it,
of course.

Jon
Jul 15 '08 #5
Well, what are you meaning by "import"? Any example code?

One good trick here is to use a generic method; I'll use C# syntax for
[my] familiarity:

public void DoSomething<T>(List<Tlist) where T : clsClass
{

}

you can now pass a List<clsClassor a List<clsSubClass>, but you
ideally want to talk about "T" inside the method. You are saying "I
have a list of [something], where that [something] is, or is derived
from, clsClass".

Marc
Jul 15 '08 #6
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)).
Jul 15 '08 #7
Yes but I should be able to Import a list of Bananas into a list of Fruits?
But it doesn't work?

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:21**********************************@l42g2000 hsc.googlegroups.com...
What exactly would you expect an import to do? You just can't treat a
list of bananas as if it's a general list of fruit. You can create a
new list of fruit and copy the contents of a list of bananas into it,
of course.

Jon
Jul 15 '08 #8
Ooops: The Import function is one we created ourselves: It takes a
BaseList(Of T) as argument.

"Marc Gravell" <ma**********@gmail.comwrote in message
news:d8**********************************@79g2000h sk.googlegroups.com...
Well, what are you meaning by "import"? Any example code?

One good trick here is to use a generic method; I'll use C# syntax for
[my] familiarity:

public void DoSomething<T>(List<Tlist) where T : clsClass
{

}

you can now pass a List<clsClassor a List<clsSubClass>, but you
ideally want to talk about "T" inside the method. You are saying "I
have a list of [something], where that [something] is, or is derived
from, clsClass".

Marc

Jul 15 '08 #9
On Jul 15, 2:32*pm, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
Ooops: The Import function is one we created ourselves: It takes a
BaseList(Of T) as argument.
And what does it do, exactly? It's hard to say why something doesn't
work without seeing it...

Jon
Jul 15 '08 #10
This code should do it. MyList1 will be a different List to MyList2, but the
elements inside will be the same. Changes to the membership of MyList2 will
not be reflected in MyList1, but changes to properties of the members in each
should be:

Dim MyList1 as New List(Of clsClass)
Dim MyList2 as New List(Of clsSubClass)
....
'Copy MyList2 into MyList1
MyList1.Clear
For i As Integer = 0 To MyList2.Count -1
MyList1.Add MyList2.Item(i)
Next i

--
David Streeter
Synchrotech Software
Sydney Australia
"Pieter" wrote:
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?
Thanks a lot in advance,
Pieter
Jul 16 '08 #11
On 15 Jul, 14:32, "Pieter" <pieterNOSPAMcou...@hotmail.comwrote:
Ooops: The Import function is one we created ourselves: It takes a
BaseList(Of T) as argument.
So the generic method approach can be used (see below, again, using C#
syntax). Alternatively, in .NET 3.5 the LINQ "Cast" method can be used
as a one-liner, even with a regular List<T>:

fruits.AddRange(bananas.Cast<Fruit>());

Marc

== code ===

public class MyList<T: List<T{
public void Import<TOther>(IEnumerable<TOtherlist)
where TOther : T {
foreach (TOther other in list) {
Add(other);
}
}
}
abstract class Fruit { }
class Banana : Fruit { }
class Tomato : Fruit { }

static void Main() {
MyList<Bananabananas = new MyList<Banana>();
bananas.Add(new Banana());
bananas.Add(new Banana());

MyList<Fruitfruits = new MyList<Fruit>();
fruits.Add(new Tomato());
fruits.Import(bananas);
}
Jul 16 '08 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Hilde Roth | last post by:
This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = ,,], is there a handy syntax for retrieving the ith item of every sublist? I know about for i...
7
by: Klaus Neuner | last post by:
Hello, I need a function that converts a list into a set of regexes. Like so: string_list = print string_list2regexes(string_list) This should return something like:
4
by: blrmaani | last post by:
Here is what I want: string s1 = "This is a list of string"; list<string> s2 = s1.some_method(); Now, I should be able to traverse list s2 and get each member ( which is of type 'string' ). ...
19
by: Eduardo Bezerra | last post by:
Hi, I'm looking for an efficient way to create the oposite of a list of numbers. For example, suppose I have this list of numbers: 100 200 300
9
by: incredible | last post by:
how to sort link list of string
6
by: Tekkaman | last post by:
I have a list of lists and I want to define an iterator (let's call that uniter) over all unique elements, in any order. For example, calling: sorted(uniter(, , ])) must return . I tried the...
12
by: A.B. | last post by:
Hi, I have various lists I want to go through, at different paces and I want to control that with a list of enumerators. I have the following: List<List<DataEntry>mydata = new...
8
by: Spoon | last post by:
Hello, Could someone explain why the following code is illegal? (I'm trying to use a list of (C-style) arrays.) #include <list> typedef std::list < int foo_t; int main() { int v = { 12, 34...
7
by: DippyDog | last post by:
My problem is the subject line. Basically, my thinking was that, given class TestSpec1 inherits from class TestBase, since I can do this... Dim tst As TestBase = GetTestObj() Function...
11
by: Pieter | last post by:
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.