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; }
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With