Generic methods let us have a custom return type. As you're not using that, i.e. your return type is void
, then it doesn't actually need to be a generic method at all:
public void DoSomething(BaseClass myInstance){
// Instance it and cast to a BaseClass:
BaseClass obj=(BaseClass)Activator.CreateInstance(myInstance.GetType(),param1,param2);
// Do anything else with obj.
}
As you say you've already got an existing object, then that is called like so:
DoSomething(thatObject);
Alternatively - this is the more common form - define a virtual Clone() method:
public class BaseClass{
public virtual BaseClass Clone(){
return new BaseClass();
}
}
public class MyClass : BaseClass{
public override BaseClass Clone(){
return new MyClass();
}
}
...
BaseClass myClone=thatObject.Clone();
If we were going to return the newly created object, then that's something a little different. It can make good use of generics:
public T DoSomething<T>() where T:BaseClass{
// Instance it and cast to T:
T obj=(T)Activator.CreateInstance(typeof(T),param1,param2);
// Do anything else with obj.
return obj;
}
With our call like this:
MyClass myClass=DoSomething<MyClass>();
This can't be done with a runtime known type because then the return type is unknown too.
Here's an example of that last one in action.