Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a List<interface> to List<concrete>?

I have an interface defined as:

public interface MyInterface {      object foo { get; set; }; } 

and a class that implements that interface:

public class MyClass : MyInterface {      object foo { get; set; } } 

I then create a function that returns a ICollection like so:

public ICollection<MyClass> Classes() {     List<MyClass> value;      List<MyInterface> list = new List<MyInterface>(         new MyInterface[] {             new MyClass {                 ID = 1             },             new MyClass {                 ID = 1             },             new MyClass {                 ID = 1             }         });      value = new List<MyClass>((IEnumerable<MyClass>) list);      return value; } 

It would compile but would throw a

Unable to cast object of type 'System.Collections.Generic.List1[MyInterface]' to type 'System.Collections.Generic.IEnumerable1[MyClass]'.

exception. What am I doing wrong?

like image 515
acermate433s Avatar asked May 16 '11 15:05

acermate433s


People also ask

Can we create list of interface?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.

Is list an interface in C#?

The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.


1 Answers

A List<MyInterface> cannot be converted to a List<MyClass> in general, because the first list might contain objects that implement MyInterface but which aren't actually objects of type MyClass.

However, since in your case you know how you constructed the list and can be sure that it contains only MyClass objects, you can do this using Linq:

return list.ConvertAll(o => (MyClass)o); 
like image 140
JSBձոգչ Avatar answered Oct 02 '22 09:10

JSBձոգչ