Why the method cannot declare the return type of `List <IMyInterface>` and return a specific class that implements it
I have the following interface
public interface IMyInterface
{
// Some method and property signatures
}
I have the following class implementing the above interface
public class MyClass : IMyInterface
{
// Some methods and properties as declared by IMyInterface
}
Then I have this method in some random class that I want to return a list of objects that implement IMyInterface
. In this particular implementation, these objects are instances MyClass
.
public List<IMyInterface> getItems(int id)
{
return new List<MyClass>();
}
This will lead to a compilation error (apparently, in real time also in Visual Studio)
Cannot implicitly convert the type 'System.Collections.Generic.List <MyClass>' to 'System.Collections.Generic.List <IMyInterface>'
, , # .
public List<IMyInterface> getItems(int id)
{
return new List<MyClass>().Cast<IMyInterface>().ToList();
}
, , -, ; . # Aequitarum Custos , .
- ?
, T
List<T>
. IEnumerable<out T>
:
out T
.
. , , .
, , getItems
:
public IEnumerable<IMyInterface> getItems(int id)
{
return new List<MyClass>() as IEnumerable<IMyInterface>;
}
, Base
Parent
, , List<Base>
List<Parent>
. IList<T>
, List<T>
(# , ).
, : http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
List<T>
, :
List<Parent> list = new List<Base>();
, ?
list.Add(new OtherBase());
, , , .
Consider the following example:
public interface IAnimal
{
}
public class Cat : IAnimal
{
}
public class Dog : IAnimal
{
}
And you are the equivalent method:
public List<IAnimal> getAnimals()
{
return new List<Dog>();
}
// You just Dog'd a list of Cats
IEnumerable<Cat> cats = getAnimals();