Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a generic List<T> to an Interface based List<T>

I am sure I am missing something simple, however I am trying to convert a strongly typed list of objects that all implement an interface in to a list of that interface type.

Below is a sample to demonstrate the error:

public void ExampleCode(){
    List<Cube> cubes = new List<Cube>();
    List<Shape> allShapes;
    allShapes = cubes;//Syntax Error
    allShapes = (List<Shape>)cubes;//Syntax Error  
}

public class Cube : Shape
{
    public int ID { get; set; }
    public int Sides { get; set; }
}

public interface Shape
{
  int ID { get; set; }
  int Sides { get; set; }
}
like image 588
John Avatar asked Feb 16 '10 11:02

John


People also ask

Can an interface be generic?

A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument.

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.

Can we have a list of interface?

It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming.


1 Answers

Instead of casting like that, try:

allShapes = cubes.Cast<Shape>().ToList();

You need .NET 3.5 for this. I believe the Cast extension method can be found in System.Linq.

like image 129
Dave Markle Avatar answered Sep 26 '22 01:09

Dave Markle