Rick Su
Rick Su

Reputation: 16440

C# Cannot convert from `Inherited Class` to `Base Class`

I've got the following code:

Simple Classes

public class Transport { }
public class Car : Transport { }
public class Bus : Transport { }

Wrapper Class

public class Wrapper<T> where T : Transport
{
    public T Vehicle { get; set; }
    public void Brake() { }
    public void Accelerate() { }
}

public class BusWrapper : Wrapper<Bus>
{
    public void PickupPassenger() { }
}

public class CarWrapper : Wrapper<Car>
{
    public void GoRacing() { }
}

This is what I'm trying which gave me compilation error:

List<Wrapper<Transport>> list = new List<Wrapper<Transport>>();

list.Add(new CarWrapper());
list.Add(new BusWrapper());

list.ForEach(wrapper =>
{
    wrapper.Accelerate();
    if (wrapper is CarWrapper)
        ((CarWrapper)wrapper).GoRacing();
    else if (wrapper is BusWrapper)
        ((BusWrapper)wrapper).PickupPassenger();

    wrapper.Brake();
});

Error

cannot convert from 'CarWrapper' to 'Wrapper<Transport>'
cannot convert from 'BusWrapper' to 'Wrapper<Transport>'

Question

What am I doing wrong here, any workaround for what I'm trying to achieve here.

Thanks in advance.

Upvotes: 2

Views: 3279

Answers (1)

Enigmativity
Enigmativity

Reputation: 117009

You are making the mistake of assuming that if Car inherits from Transport then Wrapper<Car> also inherits from Wrapper<Transport>. It does not.

You need to define IWrapper<out T> and use that for your list. Then this kind of covariance can work.

Upvotes: 2

Related Questions