Casting, generics and interface issue

A

amaca

I have a class, MyClass, which implements two interfaces, IThis and IThat. I
have a list of that class implemented as a generic,
List myList = List<MyClass>.

Can I cast myList so that it looks like a List of IThis (which one chunk of
code needs) and as a List of IThat (which another chunk of code needs)?

I'm not sure whether I don't understand the syntax for casts or have
misunderstood how to implement Generics and Interfaces. Or have I just
designed and coded my way down a blind alley?

Andrew
 
W

wackyphill

Sure,

but dont cast the whole list just cast each item as you use it.

foreach(object o in myList)
{
if( o is IList)
{
IList i = (IList)o;
//Use i;
}
else
{
//Trouble
}
}
 
M

Mattias Sjögren

Can I cast myList so that it looks like a List of IThis (which one chunk of
code needs) and as a List of IThat (which another chunk of code needs)?

You can't cast a List<MyClass> to a List<IThis> no. Even if MyClass
implements IThis there's no inheritance relation between the List
types.


Mattias
 

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