c# - Cannot implicitly convert type -


i have program has superclass vehicle , has 3 classes inheriting car,truck,minibus need take instances of classes , display them in listbox on main form 'frmhire' have class called fleet this.

i keep getting error,

cannot implicitly convert type app1.vehicle app1.car. explicit conversion exists (are missing cast?)

private void lstfleet_selectedindexchanged(object sender, eventargs e)     {         /*          * method used control list box          * called when row selected user, displays frmcar          * 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();         }     } 

given list might contain cars, trucks or minibusses, can assume can take elementat(index) , cast car, can you?

presumably vehicle elementat(index), , if know car can explicitly cast car, implicit cast have here causing issue.

so, either need (if know sure they're car instances , else exception)...

car mycar = (car)myfleet.fleet.elementat(index); 

... or need deal vehicle...

vehicle myvehicle = myfleet.fleet.elementat(index); 

if want test whether item car (and different if not) this...

car mycar = myfleet.fleet.elementat(index) car; if (mycar != null) {     // car } 

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -