Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a certain type is an Action delegate

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?

like image 722
Steven Jeuris Avatar asked Mar 01 '11 03:03

Steven Jeuris


People also ask

What is the difference between action and delegate?

The only difference between Action Delegates and Function Delegates is that Action Delegates does not return anything i.e. having void return type.

What Is an Action delegate?

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.

What is the delegate in C#?

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.

Is func a delegate?

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter.


1 Answers

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.

like image 95
BrokenGlass Avatar answered Sep 21 '22 15:09

BrokenGlass