Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert method group '' to non-delegate type 'System.Delegate'. Did you intend to invoke the method?

Tags:

c#

delegates

I'm trying to store a function reference in a Delegate type for later use.

Here's what I'm doing:

class Program
{
    static void Test()
    {

    }

    static void Main(string[] args)
    {
        Delegate t= (Delegate)Test;
    }
}

In this I'm getting following error:

Cannot convert method group 'Test' to non-delegate type 'System.Delegate'.
Did you intend to invoke the method?

Why is this happening?

like image 898
Arsen Zahray Avatar asked Mar 04 '13 15:03

Arsen Zahray


2 Answers

You really shouldn't ever use the type Delegate to store a delegate. You should be using a specific type of delegate.

In almost all cases you can use Action or Func as your delegate type. In this case, Action is appropriate:

class Program
{
    static void Test()
    {

    }

    static void Main(string[] args)
    {
        Action action = Test;

        action();
    }
}

You can technically get an instance of Delegate by doing this:

Delegate d = (Action)Test;

But actually using a Delegate, as opposed to an actual specific type of delegate, such as Action, will be hard, since the compiler will no longer know what the signature of the method is, so it doesn't know what parameters should be passed to it.

like image 154
Servy Avatar answered Nov 07 '22 08:11

Servy


What you are trying to do here is cast the method group Test to something. As per the spec, the only legal cast for a method group is casting it into a delegate type. This can be done either explicitly:

var t = (Delegate)Test;

or implicitly:

Delegate t = Test;

However, as the documentation says, System.Delegate itself is... not a delegate type:

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types.

The compiler detects this and complains.

If you want to cast a method group to a delegate you will have to specify a delegate type with a compatible signature (in this case, Action).

like image 38
Jon Avatar answered Nov 07 '22 07:11

Jon