I'm trying to check whether a given type is an action delegate, regardless of the amount of parameters.
The following code is the only way I know how to do this.
public static bool IsActionDelegate( this Type source )
{
return source == typeof( Action ) ||
source.IsOfGenericType( typeof( Action<> ) ) ||
source.IsOfGenericType( typeof( Action<,> ) ) ||
....
source.IsOfGenericType( typeof( Action<,,,,,,,,,,,,,,,> ) );
}
IsOfGenericType()
is another extension method of mine, which does what it says, it checks whether the type is of the given generic type.
Any better suggestions?
The only difference between Action Delegates and Function Delegates is that Action Delegates does not return anything i.e. having void return type.
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. For example, the following delegate prints an int value.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter.
If you are just after the delegates that have a void return type you could do the following:
public static bool IsActionDelegate(Type sourceType)
{
if(sourceType.IsSubclassOf(typeof(MulticastDelegate)) &&
sourceType.GetMethod("Invoke").ReturnType == typeof(void))
return true;
return false;
}
This would not distinguish between Action
and MethodInvoker
(or other void delegates for that matter) though. As other answers suggest you could examine the type name, but that kinda smells ;-)
It would help if you could clarify for what reason you want to identify Action
delegates, to see which approach would work best.
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