Stig Gunnarsson

Stig Gunnarsson

  • NA
  • 11
  • 1.4k

How to get a new copy from a polymorfic list?

Mar 16 2017 12:06 PM
I have a base class Car. From this I derive some 25 classes of CarTypes (Ford, BMW and so on), and from these I derive some 10 classes of carModels.
Now I have a List<Car> cars, that can contain 250 different carModel instances. I want to retreive a new instance of the carModel at position index in list, but NOT an EMPTY instance but a COPY of the carModel at  cars[index].
All of the 250 CarModel classes has a copy constructor. I can use reflection to get the type
Type t = (Typeof) cars[index]; Then I can create an EMPTY instance with
activator.CreateInstance(t); but HOW do I invoke the copy constructor of the element at position index for copy OR can I use get properties to work on a list of Car? 

Answers (3)