What's the best way (in .NET 4) to create an instance of a type determined at runtime.
I have an instance method which although acting on a BaseClass object may be called by instances of its derived classes. I require to create another instance of the same type as this
within the method. Overloading the Method for each derived class is not practical as it is fairly involved and would be more efficient to keep to the single implementation.
public class BaseClass
{
//constructors + properties + methods etc
public SomeMethod()
{
//some code
DerivedClass d = new DerivedClass(); //ideally determine the DerivedClass type at run-time
}
}
I've read a bit about reflection or using the dynamic keyword but i don't have experience with these.
This should create a new instance, on the other hand I wonder the why you trying to do this.