Polymorphism - What am I not getting?

c#, c#-4.0, polymorphism

Solution

This is a question of variance, not polymorphism.

If a List-of-Foo was also an IList-of-IBar, the following would work:

class Another : IBar {}
IList<IBar> list = new List<Foo>();
list.Add(new Another());

Then we've added an Another to a list of Foo. Which is an error. The compiler stopped you making a mistake.

Note that recent compilers / .net versions support variance via "in"/"out". So a List-of-Foo is fine as an IEnumerable-of-IBar. Because that is guaranteed to only return Foo (not accept them), and all Foo are also IBar - hence it is safe.

Problem

I am having an issue with polymorphism in C#. I have an object that implements an interface, however I cannot represent a collection of the objects as a collection of interfaces. This flies in the face of my understanding of polymorphism. So I was wondering where I have gone wrong. ``` [TestFixture] class Tester { [Test] public void Polymorphism() { var list = new List<Foo> {new Foo {Name = "Item"}}; Assert.That(list, Is.InstanceOf<IList>()); Assert.That(list[0], Is.InstanceOf<Foo>()); Assert.That(list[0], Is.InstanceOf<IBar>()); // why are the rest true but this false? Assert.That(list, Is.InstanceOf<IList<IBar>>()); } } internal interface IBar { } internal class Foo : IBar { public string Name { get; set; } } ```

Original source