how to pass an Action<in T> with a derived class as the Action parameter?
c#
Solution
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:
- Do compile time checking to ensure the type you use is `BaseClass` or a type deriving from it. You won't get runtime errors because the type doesn't extend `BaseClass`.
- Do compile time checking to ensure that the type has a parameterless constructor, rather than throwing an exception at runtime if one doesn't exist.
- Do compile time checking to ensure that the method provided for the `Action` accepts a parameter appropriate for the type used, instead of throwing an exception at runtime if the type isn't appropriate.
Problem
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); ```