-3

I have no clue why the constuctor of the Car class does not compile.

"Cannot implicitly convert type 'System.Collections.Generic.List<ConsoleApp1.Tire>' to 'System.Collections.Generic.List<ConsoleApp1.IWheel>'"

using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            IVehicle myCar = new Car();
            myCar.AddWheel();
            var countWheels = CountWheels(myCar);
        }

        static int CountWheels(IVehicle vehicle)
        {
            return vehicle.Wheels.Count;
        }
    }

    // Interfaces
    public interface IVehicle
    {
        public List<IWheel> Wheels { get; set; }
        public void AddWheel();
    }
    public interface IWheel
    {
        public int Radius { get; set; }
    }

    // Abstract base classes
    public abstract class Vehicle : IVehicle
    {
        public List<IWheel> Wheels { get; set; }

        public abstract void AddWheel();
    }
    public abstract class Wheel : IWheel
    {
        public int Radius { get; set; }
    }

    // Implementations
    public class Car : Vehicle
    {
        public override void AddWheel()
        {
            var newTire = new Tire();
            this.Wheels.Add(newTire);
        }
        public Car()
        {
            this.Wheels = new List<Tire>();
        }
    }

    public class Tire : Wheel
    {
        public int MinimumPressure { get; set; }
    }
}

Every Wheel implements IWheel and every Tire is a Wheel. Thereby every Tire implements IWheel implicitly, right?

So, why cant I assign a List of Tires to a List of IWheels?

Thank you for your help guys. I obviously completely misunderstood something about polymorphism.

Ingmar
  • 1,525
  • 6
  • 34
  • 51
  • Because they are different classes and has no connection ... lets assume that you would have `TireIsNotWheel : IWheel` ...if you could assign `List` to `List` then you could add to it instance of `TireIsNotWheel` – Selvin Oct 23 '20 at 07:28
  • @Selvin: thank you. Still didn't make "click" in my mind :( Is there something obvious to change in my code to make it compile? I tried several things already. – Ingmar Oct 23 '20 at 07:37
  • 1
    change Tire to IWheel in List generic parameter? – Selvin Oct 23 '20 at 07:39
  • `Tire : Wheel` seems like an odd inheritance, since a tyre is not a type of wheel. – ProgrammingLlama Oct 23 '20 at 07:43

1 Answers1

2

Since Wheels is declared as

public List<IWheel> Wheels { get; set; }

Just use IWheel instead

public Car()
{
    this.Wheels = new List<IWheel>();

Everything will work as expected

TheGeneral
  • 79,002
  • 9
  • 103
  • 141