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.
You are looking for
Activator.CreateInstance(there are also other overloads, such as this one that accepts constructor arguments). So you could writeThere may be a problem here in that
anotherOneLikeMeis going to be typed asobject, so unless you intend to cast it to a common base class (e.g.BaseClassin your example) there’s not much that you can do with it.