I'm working with C#5/.NET 4.5 in Visual Studio 2013 Pro on Windows 7.
I'd like to work with collections of items where the only requirement is that the items implement a specific interface. The items in the collection will not necessarily be part of a common inheritance tree (i.e. the collection will not be based on a common ancestor), they could be arbitrary classes but will all implement the specified interface (so the goal is to base the collection on the common interface that they all implement).
I'm having trouble with this. If I have a collection of items which implement the desired interface, I'm unable to pass that collection to a method which requires a collection based on the interface.
Here's some code to make this more concrete.
using System.Collections.Generic;
class Test
{
public interface IDrawable
{
void Draw();
}
public class Shape : IDrawable
{
public void Draw() {}
}
public void DrawItems(List<IDrawable> itemsToDraw) {}
public Test()
{
List<Shape> shapes = new List<Shape>();
DrawItems(shapes);
}
}
The call to DrawItems generates a compiler error. The method is expecting a collection of items implementing IDrawable. I'm passing in a collection of Shape objects. Since the Shape objects do implement IDrawable, I was hoping I could get away with this.
Looks like this will not work, but I'm trying to understand why. I looked up info on covariance and contravariance, but didn't find anything specifically addressing this case.
Any ideas or info on why this doesn't work?