4

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?

3 Answers 3

8

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.

2

Try

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

you can use the IEnumerable<T> extension method Cast

Object.X = yourList.Cast<ITopics>().ToList();
1
  • That gives you an IEnumerable<T> not an IList<T>. Apr 22, 2009 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.