How to pass an Action <in T> with a derived class as an Action parameter?

Given:

class BaseClass {} class DerivedClass : BaseClass {} 

I want to write a function that can take an action with the 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 to AnotherFunction, whose parameter is DerivedClass:

 void AnotherFunction(DerivedClass x) { } 

How do I call MyFunction? The following is invalid due to the AnotherFunction argument:

 MyFunction(typeof(DerivedClass), AnotherFunction); 
+6
source share
1 answer

If at all possible, try using generics instead:

 void MyFunction<T>(Action<T> DoAction) where T : BaseClass, new() { DoAction(new T()); } 

Then you can simply write:

 MyFunction<DerivedClass>(AnotherFunction); 

It will be:

  • Check compile time to ensure the type you are using is BaseClass or a type derived from it. You will not get runtime errors because the type does not extend BaseClass .
  • Check compilation time to make sure that the type has a constructor without parameters, and does not throw an exception at runtime if it does not exist.
  • Check compilation time to ensure that the method provided for Action accepts a parameter that is appropriate for the type being used, rather than throwing an exception at run time if the type is not suitable.
+11
source

Source: https://habr.com/ru/post/944245/


All Articles