0

I have 2 objects and a mutual interface

public interface IMyInterface { ... }
public class MyClass1 : IMyInterface { ... }
public class MyClass2 : IMyInterface { ... }

Then I have a function that accepts a list of IMyInterface

public void MyFunction(List<IMyInterface> myObjects) { ... }

If I were to call this function using List<MyClass1> or List<MyClass2> I get an error saying I cannot convert List<MyClass1> to List<IMyInterface>, however, if I changed my function signature to -

public void MyFunction(IEnumerable<IMyInterface> myObjects) { ... }

there is no longer an error. My question is why does this work for IEnumerable and not a concrete List?

Adjit
  • 10,134
  • 12
  • 53
  • 98
  • A bas class number properties <= inherited class number of properties. Sop you cannot take a class with more properties and cast to a smaller object. You can take a smaller object a cast to a larger object. – jdweng Nov 24 '21 at 17:08

1 Answers1

1

This is due to covariance and contravariance. The problem is that your method might do this:

public void AddItem(List<IAnimal> animals)
{
    animals.Add(new Tiger());
    animals.Add(new Giraffe());
}

No matter whether the caller passes in a List<Giraffe> or List<Tiger>, this would end up inserting the wrong type into the list.

Stephen Jennings
  • 12,494
  • 5
  • 47
  • 66