SoFunction
Updated on 2025-03-07

Analysis of C# anonymous method and Delegate type conversion errors

This article analyzes the C# anonymous method and Delegate type conversion errors. Share it for your reference. The specific analysis is as follows:

Problem description

Anonymous methods appear in C# 2.0, which saves us the energy to maintain the code context to a certain extent, and does not need to think about what name to give a method is more appropriate. Some methods of FCL require that a parameter of type Delegate be passed, such as or method:

Copy the codeThe code is as follows:
public object Invoke(Delegate method);

public IAsyncResult BeginInvoke(Delegate method);

In this case, if you do not use an anonymous method, you need to declare a delegate void DoSomething() method on the code, and then you can use lambda expressions or delegate to implement DoSomething() in the Invoke method.

Copy the codeThe code is as follows:
delegate void DoSomething();
private void App()
{
    (new DoSomething(() =>
    {
//Specific operations of DoSomething
    }));
}

This is OK, but it is better to use anonymous method, at least it looks more concise.

Copy the codeThe code is as follows:
private void App()
{
    (delegate
    {
//Specific operations of DoSomething
    });
}

The above code will make an error during compilation: Cannot convert anonymous method to type because it is not a delegate type. The method requires a delegate parameter, and now only an anonymous method is passed. The most fundamental reason for this error is that when the compiler handles anonymous method, he cannot infer what type of delegate method returns, so he does not know what kind of delegate to return.

Solution

To solve the above problem, fundamentally speaking, it is to specify what type of delegate this anonymous method will return. There are several methods:

1. Use MethodInvoke or Action

Copy the codeThe code is as follows:
private void App()
{
    ((MethodInvoker)delegate()
    {
//Specific operations of DoSomething
    });
}
private void App()
{
    ((Action)delegate()
    {
//Specific operations of DoSomething
    });
}

MethodInvoke and Action are both delegates with empty return type.

2. You can define an Invoke extension method for Control

Copy the codeThe code is as follows:
public static void Invoke(this Control control, Action action)
{
    ((Delegate)action);
}

When calling, you can call it like this:

Copy the codeThe code is as follows:
//Use Delegation
(delegate { //DoSomething  here});
//Use lambda expression
(()=>{ //DoSomething here});

I hope this article will be helpful to everyone's C# programming.