Creating an instance of a class with the same type as an existing object
base-class, c#
Solution
d2 = (Base)Activator.CreateInstance(d1.GetType());
Problem
I would like to instantiate an instance of a class based on the type of another instance that is part of a simple type hierarchy. ``` public abstract class Base { } public class Derived1 : Base { } public class Derived2 : Base { } ``` This is easy to do with the following code ``` Base d1 = new Derived1(); Base d2; if (d1 is Derived1) { d2 = new Derived1(); } else if (d1 is Derived2) { d2 = new Derived2(); } ``` However, is it possible to achieve this without an `if...else if...` chain by (for example) using reflection to get hold of the constructor of `d1` (in my example) and using it to instantiate another instance of whatever type `d1` might happen to be?