c# - Creating an instance of a class with the same type as an existing object -


i instantiate instance of class based on type of instance part of simple type hierarchy.

public abstract class base { }  public class derived1 : base { }  public class derived2 : base { } 

this easy following code

base d1 = new derived1();  base d2;  if (d1 derived1) {     d2 = new derived1(); } else if (d1 derived2) {     d2 = new derived2(); } 

however, possible achieve without if...else if... chain (for example) using reflection hold of constructor of d1 (in example) , using instantiate instance of whatever type d1 might happen be?

d2 = (base)activator.createinstance(d1.gettype()); 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -