I am having a problem understanding how polymorphism works when using generics. As an example, I have defined the following program:
public interface IMyInterface
{
void MyMethod();
}
public class MyClass : IMyInterface
{
public void MyMethod()
{
}
}
public class MyContainer<T> where T : IMyInterface
{
public IList<T> Contents;
}
I can then do this, which works just fine:
MyContainer<MyClass> container = new MyContainer<MyClass>();
container.Contents.Add(new MyClass());
I have many classes that implement MyInterface. I would like to write a method that can accept all MyContainer objects:
public void CallAllMethodsInContainer(MyContainer<IMyInterface> container)
{
foreach (IMyInterface myClass in container.Contents)
{
myClass.MyMethod();
}
}
Now, I'd like to call this method.
MyContainer<MyClass> container = new MyContainer<MyClass>();
container.Contents.Add(new MyClass());
this.CallAllMethodsInContainer(container);
That didn't work. Surely, because MyClass implements IMyInterface, I should be able to just cast it?
MyContainer<IMyInterface> newContainer = (MyContainer<IMyInterface>)container;
That didn't work either. I can definitely cast a normal MyClass to IMyInterface:
MyClass newClass = new MyClass();
IMyInterface myInterface = (IMyInterface)newClass;
So, at least I haven't completely misunderstood that. I am unsure exactly how I am to write a method that accepts a generic collection of classes that conform to the same interface.
I have a plan to completely hack around this problem if need be, but I would really prefer to do it properly.
Thank you in advance.