Cannot convert source type 'List <Person>' to IList <ISomething>

This may be a fairly simple question, but for me it does not make sense.

Given this class:

public class Person : ICloneable { public object Clone() { Console.WriteLine("Hello, world"); return new Person(); } } 

Why is this normal?

 List<Person> people = new List<Person> { new Person() }; IEnumerable<ICloneable> clonables = people; 

But is that not so?

 List<Person> people = new List<Person> { new Person() }; IList<ICloneable> clonables = people; 

Why can I designate IEnumerable IClonable, but not IList ICloneable?

+7
casting c #
source share
3 answers

This is called covariance. Eric Lippert and John Skeet (among others) gave some useful explanations for covariance (and its twin, contravariance) in answering this question: The difference between covariance and contravariance

Basically , you can list the Person list in the same way as if you had done on the ICloneable list, no problem, because you cannot change the listing. But you cannot assign your Person list to an ICloneable , because then you could try, for example, inserting some other derivative of ICloneable , which would lead to a strong violation of the -Security type.

+11
source share

IList :

 public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable 

IEnumerable :

 public interface IEnumerable<out T> : IEnumerable 

Pay attention to out in IEnumerable ? IEnumerable<T> covariant

+5
source share

I had another answer that was wrong. I apologize. Thanks Matt for that.

The error message is quite misleading. This suggests that the actor will work, but does not. The problem is that to convert Person to ICloneable, you may need to adjust the pointer so that the virtual function table is correct for the generic ICloneable. This means that each item in the list may need to be adjusted. The real solution is to use ToList:

  IList<ICloneable> clonablesA = people.ToList<ICloneable>(); 

Ignore some of the comments below since I completely deleted my first answer.

+2
source share

All Articles