Given:
class BaseClass {}
class DerivedClass : BaseClass {}
I want to write a function that can accept an Action with a BaseClass parameter. The function will create an object of the specified type and pass it to the Action.
void MyFunction(Type type, Action<BaseClass> DoAction)
{
BaseClass obj = (BaseClass)Activator.CreateInstance(type);
DoAction(obj);
}
I want to pass in AnotherFunction whose parameter is a DerivedClass:
void AnotherFunction(DerivedClass x)
{
}
How should I call MyFunction? The following is invalid due to the AnotherFunction argument:
MyFunction(typeof(DerivedClass), AnotherFunction);
If at all possible, try to use generics instead:
void MyFunction<T>(Action<T> DoAction) where T : BaseClass, new()
{
DoAction(new T());
}
Then you can just write:
MyFunction<DerivedClass>(AnotherFunction);
This will:
BaseClass
or a type deriving from it. You won't get runtime errors because the type doesn't extend BaseClass
.Action
accepts a parameter appropriate for the type used, instead of throwing an exception at runtime if the type isn't appropriate.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With