简体   繁体   中英

Generic Interface and Class / up casting is not working

I'm trying to understand basic Inheritance and polymorphism concepts. but I'm stuck in one scenario.

Consider the following code:

Interface:-

public interface IObject<T>
{
    T Value { get; }
}

Implementation:-

public class MyObject<T> : IObject<T>
{
    private T value;

    public MyObject(T value)
    {
        this.value = value;
    }

    public T Value => value;
}

public class SquareObject : MyObject<Square>
    {
        public SquareObject(Square square) : base(square)
        {

        }
    }

Helper Classes And Interface:-

public interface IShape
{

}

public abstract class Shape : IShape
{
    public abstract int Area();
}

public class Square : Shape
{
    int length;

    public Square(int len)
    {
        length = len;
    }

    public override int Area()
    {
        return length * length;
    }
}

My question is when I do up casting of square object to shape, it's working fine.

IShape shape = new Square(5);

But when I do the same using MyObject generic class, it doesn't work.

var square = new Square(5);
IObject<IShape> gShape = new MyObject<Square>(square);

It says "Cannot implicitly convert type MyObject<Square> to IObject<IShape> ". May be, I can fix it using casting. Can it be possible without casting?

Similarly, I'm also not able to do the same using SquareObject class.

var square = new Square(5);
IObject<IShape> shapeObj = new SquareObject(square);

It says "Cannot implicitly convert type SquareObject to IObject<IShape> ". May be, I can fix it using casting. Can it be possible without casting?

You could declare your IObject interface as covariant using

public interface IObject<out T>
{
    T Value { get; }
}

Covariant means that you can assign an object implementing IObject<Derived> to a variable of type IObject<Base> . The documentation can be found here .


Without explicitly specifying covariance your MyObject<Square> is an IObject<Square> , but it can't be assigned to a variable of type IObject<IShape> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM