Generic collection casting

G

Guest

Hi,

I would like to have something like that :

IList<IUser> list2 = list1 as IList<IUser>;

where list1 is a generic collection of User ( IList list1<User>=new
List<User>() ) and where User implement the interface IUser.
But this did not work...
I thought that as User implement IUser it was possible to cast the generic
collection between the two types. Currently I ve to use a foreach loop to
populate the list2 collection :
foreach(User u in list1)
{
list2.add(u as IUser);
}

Is there a more efficient and elegant way for doing this ?

Thanks.
Yalt.
 
K

Kevin Spencer

The problem here is that while the User implements the IUser interface, and
therefore an instance of User can be cast as IUser, IList<IUser> is a *List*
of IUser, and IList<User> is a *List* of User. You're not trying to cast the
items *u=in* the list; you're trying to cast the List itself. List<User>
does not inherit List<IUser> and List<IUser> is not an interface which
List<User> Implements. Therefore, there is no casting between them.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 

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