Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Interfaces with ILIST

Tags:

c#

interface

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?

like image 329
zsharp Avatar asked Dec 31 '22 01:12

zsharp


1 Answers

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.

like image 120
Jeffrey Hantin Avatar answered Jan 01 '23 14:01

Jeffrey Hantin