List(Of clsClass1, clsClass2)?

P

Pieter

Hi,

A little bit linked to my other question: I thought it was possible to have
generic list which accept multiple types of objects. So a statement as ""Dim
MyList as List(Of clsClass1, clsClass2)" would accept instances of both
clsClass1 and clsClass2.

But, it doesn't work :) Am I simply wrong, or did I do something wrong?

Thanks a lot in advance,


Pieter
 
J

Jon Skeet [C# MVP]

A little bit linked to my other question: I thought it was possible to have
generic list which accept multiple types of objects. So a statement as ""Dim
MyList as List(Of clsClass1, clsClass2)" would accept instances of both
clsClass1 and clsClass2.

But, it doesn't work :) Am I simply wrong, or did I do something wrong?

No, it doesn't work. What would the effective type of the indexer be,
or the iterator?

Jon
 
P

Pavel Minaev

Hi,

A little bit linked to my other question: I thought it was possible to have
generic list which accept multiple types of objects. So a statement as ""Dim
MyList as List(Of clsClass1, clsClass2)" would accept instances of both
clsClass1 and clsClass2.

But, it doesn't work :) Am I simply wrong, or did I do something wrong?

If you want a list of related objects, then it is likely that they
should have a common base class (or implement some common interface).

If you _really_ want a typesafe list of unrelated objects (for
example, because ordering is relevant), then you can use the
Either<T1, T2> type from ECMA TR/89 (http://www.ecma-international.org/
publications/techreports/E-TR-089.htm):

var list = new List<Either<Class1, Class2>>();
list.Add(new Class1());
list.Add(new Class2());
foreach (var item in list)
{
if (item.IsFirst)
{
Class1 c1 = (Class1)item;
...
}
else if (item.IsSecond)
{
Class2 c2 = (Class2)item;
...
}
}

By the way, please do not use "cls" prefix for your classes - this is
against pretty much all naming conventions in the .NET land. Class
names are supposed to begin with a capital letter, and Hungarian
notation is generally frowned upon, but particularly so for type names.
 
S

SurturZ

Cheat and use a List (Of Object) !! ;-)

In your loops then use GetType and CType to process individual members.

(This approach is "wrong" for many reasons, but oh so useful)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top