2

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.

Neverever
  • 15,890
  • 3
  • 32
  • 50
  • 1
    You're trying to be covariant. – SLaks Oct 04 '12 at 02:38
  • 1
    You're probably better off using an interface in a situation like this. – Adam Plocher Oct 04 '12 at 02:41
  • possible duplicate of [Cannot Convert Derived Class to Base Class](http://stackoverflow.com/questions/1955528/cannot-convert-derived-class-to-base-class) – phoog Oct 04 '12 at 13:17
  • When you are asking a question, you should first check the similar questions identified by StackOverflow. In addition to the nearly identical question in the previous comment (which is even another problem in the transport domain), you might have found [Explicit Casting Problem](http://stackoverflow.com/q/1443341/385844) and [Generics and casting - cannot cast inherited class to base class](http://stackoverflow.com/q/3528821/385844). – phoog Oct 04 '12 at 13:21

1 Answers1

2

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.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172