Peter, Pavel,
Thanks, I modified my code to work with the IEnumerable produced by
Peter's posting and it's much cleaner than the looping I had previously done
to achieve this.
Bill
"Pavel Minaev" wrote:
> On Mar 16, 9:37 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
> wrote:
> > On Mon, 16 Mar 2009 08:24:11 -0700, wdudek <wdu...@newsgroup.nospam> wrote:
> > > I have a list (actually an IList) of objects that implement an interface
> > > and
> > > need to cast the list to a list of the intercace. Is there an easy and
> > > "clean" way to do this, I tried using a direct cast (List<IMyInterface>)
> > > myObjectList, but it threw an exception at run time. In the past I have
> > > done
> > > this with a foreach loop, but it seems like there would be some extension
> > > method to do it for me. Also I'm on the 3.5 framework.
> >
> > You can't literally do what you're asking. But, depending on your needs,
> > the Enumerable.Cast<T>() extension method might be useful to you:
> >
> > IEnumerable<IMyInterface> rgmi = myObjectList.Cast<IMyInterface>();
>
> Furthermore, if by "cast" one means "creating a new list" (which is
> the only typesafe way to do it, when dealing with List<T>), then the
> above can further be extended to:
>
> List<IMyInterface> list = myObjectList.Cast<IMyInterface>().ToList
> ();
>
> As to why a plain cast doesn't work - it's because it's not typesafe
> in the presence of any non-covariant methods such as List.Add(). For
> the theory underlying this, see here:
>
> http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
>
> (by the way, is there some FAQ for this sort of stuff that can be
> linked to from the signature?)
>
|