0

I have clases and interface like this:

public interface IPerson
{
    public string Name { get; set; }
}

public class Person : IPerson
{
    public string Name { get; set }
    public int Age { get; set; }
}

public interface IMove<T>
{
    void ChangeLocation(T obj);
}

public class Move<T> : IMove<T>
{
    public void ChangeLocation(T obj)
    {
        throw new NotImplementedException();
    }
}

And I can do stuff like this:

        IPerson p = new Person();
        IMove<Person> t1 = new Move<Person>();
        IMove<IPerson> t2 = new Move<IPerson>();

But when I'm trying to do:

IMove<IPerson> t3 = new Move<Person>();

compiler is showing error:

Cannot implicity convert type Move<Person> to IMove<IPerson>

Can you please explain why so?

surzyn
  • 131
  • 1
  • 11
  • 1
    Does this answer your question? [C# generic inheritance and covariance part 2](https://stackoverflow.com/questions/14263964/) and [Assigning List as List](https://stackoverflow.com/questions/2033912/) and [C# variance problem: Assigning List as List](https://stackoverflow.com/questions/58570948/) and [still confused about covariance and contravariance & in/out](https://stackoverflow.com/questions/3445631/) and [C# : Is Variance (Covariance / Contravariance) another word for Polymorphism?](https://stackoverflow.com/questions/1078423/) –  Aug 03 '21 at 13:00
  • 4
    To protect giraffes: `List giraffes = new List{new Giraffe()}; List animals = giraffes; animals.Add(new Lion());` – Tim Schmelter Aug 03 '21 at 13:02
  • Here you have two problems: you have Move<> and IMove<> AND Person and IPerson. You can't convert Move to IMove as is, or the opposite. You can try for example Linq Select or any other thing by hand like [Copying a List to List](https://stackoverflow.com/questions/516463/copying-a-listbaseclass-to-listderivedclass/516475) and [Convert List to List](https://stackoverflow.com/questions/1817300/convert-listderivedclass-to-listbaseclass) –  Aug 03 '21 at 13:04
  • Thank you all, Now I understand it. @TimSchmelter I love your example :) – surzyn Aug 03 '21 at 13:23

0 Answers0