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

I am trying to save a function reference in the Delegate type for later use.

That's what I'm doing:

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

In this, I get the following error:

It is not possible to convert the Test method group to a type without the System.Delegate delegate.
Did you intend to call the method?

Why is this happening?

+4
source share
2 answers

You really shouldn't use the Delegate type to store the delegate. You must use a specific type of delegate.

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

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

You can technically get an instance of Delegate by doing the following:

 Delegate d = (Action)Test; 

But in fact, using Delegate , unlike the actual specific type of delegate, for example Action , will be difficult, because the compiler will no longer know what the signature of the method is, t know what parameters should be passed to it.

+7
source

What you are trying to do here is to make the Test methods group. According to the specification, the only legal composition for a group of methods is a delegate type listing. This can be done explicitly:

 var t = (Delegate)Test; 

or implicitly:

 Delegate t = Test; 

However, since the documentation says that 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 get explicitly from the Delegate class or from the MulticastDelegate class. It is also not valid to infer a new type from a delegate type. The Delegate class is not considered a delegate type; this is the class used to get the types delegate.

The compiler detects this and complains.

If you want to pass a group of methods to a delegate, you will need to specify a delegate type with a compatible signature (in this case, Action ).

+5
source

All Articles