bettsy583
bettsy583

Reputation: 21

Cannot implicitly convert type

I have a program that has a superclass vehicle and has 3 classes inheriting from it car,truck,minibus I need to take instances of the classes and display them in a listbox on my main form 'FrmHire' I have a class called fleet for this.

I keep getting this error,

Cannot implicitly convert type App1.Vehicle to App1.Car. An explicit conversion exists (are you missing a cast?)

private void lstFleet_SelectedIndexChanged(object sender, EventArgs e)
    {
        /*
         * This method is used to control the list box
         * It is called when a row is selected by the user, it then displays frmCar
         * with the car details
         */ 
        if (lstFleet.SelectedIndex > -1)
        {
            int index = lstFleet.SelectedIndex;
            Car myCar = myFleet.fleet.ElementAt(index);
            FrmCar carGui = new FrmCar();
            carGui.car = myCar;
            carGui.Show();
        }
    }

Upvotes: 0

Views: 2275

Answers (4)

Martin Peck
Martin Peck

Reputation: 11544

Given that your list might contain Cars, Trucks or Minibusses, you can assume that you can take the ElementAt(index) and cast it to Car, can you?

Presumably you get back a Vehicle from the ElementAt(index), and if you know that it will be a car then you can explicitly cast it to Car, but the implicit cast that you have here is causing this issue.

So, you either need (if you know for sure they're all Car instances and anything else is an exception)...

Car myCar = (Car)myFleet.fleet.ElementAt(index);

... or you need to deal with this as a Vehicle...

Vehicle myVehicle = myFleet.fleet.ElementAt(index);

If you want to test whether the item is a Car (and do something different if not) then this...

Car myCar = myFleet.fleet.ElementAt(index) as Car;
if (myCar != null)
{
    // it was a car
}

Upvotes: 1

jordanbtucker
jordanbtucker

Reputation: 6078

Try this:

Car myCar = (Car)myFleet.fleet.ElementAt(index);

Upvotes: 0

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

Car myCar = (Car)myFleet.fleet.ElementAt(index);

This will throw an exception if myFleet.fleet.ElementAt(index); is not a Car. To check if it is a Car you can do if (myFleet.fleet.ElementAt(index) is Car) {...}. But the best is to use a List<Car> instead of List<Vehicle> if you're only going to store Cars in it.

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

What is the type of myFleet.fleet? I suspect it is a collection of Vehicle's and you're trying to assign one to a Car.

Upvotes: 0

Related Questions