C# - List to hold hold multiple object types inherited from the same base class -


in below example able put instances of standardcar or racecar carcollection list cast them correct data type loop through carcollection list.

i understand not possible in c#. can't find way around doesn't involve 1 class has attributes in single class. since numberofraces applies racecars seems messy having way?

i'll know if i'm working standard cars or race cars when loop through collection. below if put standardcar list, loop through list , cast standardcar cast exception.

note actual final class lot more complicated below.

class car {     public string name {get; set;} }  class racecar : car {     public int numberofraces {get; set;} }  class standardcar: car {     public bool childrenincar {get; set;} }      class carcollection {    list<car> collection {get; set;} } 

thanks help.

it possible, can add list normal, cast need test types of car returned:

// create cars racecar rcar = new racecar(); standardcar scar = new standardcar();  // add collection carcollection col = new carcollection(); col.add(rcar); col.add(scar);  // iterate foreach(car car in col.collection) {     if(car racecar)     {         racecar racecar = (racecar)car;     }     else if(car standardcar)     {         standardcar standcar = (standardcar)car;     }      // ... etc } 

you do:

car racecar 

and make sure returned value not null.

note: code not tested, should work.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -