zsharp
zsharp

Reputation: 13756

Casting Interfaces with ILIST

I have field X of type ILIST <ITopics>

I am trying to do this:

Object.X= AListOfSometypeThatInheretsITopics;

How do I properly cast the list to the Object.X?

Upvotes: 4

Views: 290

Answers (3)

Xian
Xian

Reputation: 76591

you can use the IEnumerable<T> extension method Cast

Object.X = yourList.Cast<ITopics>().ToList();

Upvotes: 0

jlembke
jlembke

Reputation: 13517

Try

object.x = IList<ITopics>.ofType<ITopics>().ToList()

Upvotes: 2

Jeffrey Hantin
Jeffrey Hantin

Reputation: 36504

This requires generic variance, which is unfortunately not possible with IList<T> because it expresses a mutable list interface. Your best bet is to either use a non-generic IList or a generic IEnumerable<T> (which is amenable to variance as of C# 4) as the field/property type, or convert it by a mechanism such as

x = inputList.OfType<ITopics>().ToList();

to obtain a list of the appropriate flavor.

Upvotes: 8

Related Questions