[C#] Delegates, anonymous methods, Lambda expressions and events

【C#】Delegate, Anonymous Method, Lambda Expression and Event

Delegation

What is a delegation?

Like a class, a delegate is a user-defined type and an abstraction of a method (function). In layman’s terms, a delegate is a representative of a method (function) of a custom type.

Declaration delegation

//<access modifier> delegate <function return type> <custom delegate name> (function return parameter);
//Define a delegate whose return value is null and only has 1 parameter and the parameter is of type int
private delegate void MyDelegate(int a);
//Define a delegate whose return value is double and has 2 parameters whose parameters are string and bool
public delegate double MySDelegate(string a, bool b);
Note: Delegates can be declared inside and outside the class. A delegate can have parameters or no parameters. The return type can be null or something else.

Instantiation of the delegate

The delegate object must be created using the new keyword, and the method (function) of the type defined when declaring the delegate must be passed in as the registration method.

MyDelegate myDelegate = new MyDelegate(Method1);// delegate instantiation

If the registration method is not passed in, an error will be reported:

Use of delegation

In the following code, the declaration returns a delegate with a string parameter and a return value of null, and the Perform method (function) of the Student instance object stu1 is used as a registration method to instantiate the delegate object.

class Student
{<!-- -->
    public void Perform(string content)
    {<!-- -->
        Console.WriteLine("Students perform content about " + content + "");
    }
}

class Program
{<!-- -->
    private delegate void PerformDelegate(string content);

    static void Main(string[] args)
    {<!-- -->
        Student stu1 = new Student();
        PerformDelegate performDelegate = new PerformDelegate(stu1.Perform);
        performDelegate("Writing a program");//Output: Students perform content about writing a program
        Console. ReadLine();
    }
}

Delegated unicast and multicast

A delegate can represent multiple methods (functions), and the delegate object uses “=” for assignment. At this time, the delegate has only one method, which is called unicast.
The delegate object can use “+=” to add the same type of method (function), or use “-=” to remove the method (function) in the delegate object, these operations will make the delegate contain multiple methods (function), called multicast , also known as multicast.

private delegate string MethodDelegate(int a, int b);

static void Main(string[] args)
{<!-- -->
    MethodDelegate methodDelegate = Method1;//Unicast
    methodDelegate += Method2;
    methodDelegate += Method1;
    methodDelegate -= Method1;
    methodDelegate += Method2;
    methodDelegate(1, 2);
    // output:
    //Method1 : 3
    //Method2: 2
    //Method2: 2
    Console. ReadLine();
    
}

private static string Method1(int a, int b)
{<!-- -->
    Console.WriteLine("Method1 : " + (a + b));
    return "" + (a + b);
}

private static string Method2(int a, int b)
{<!-- -->
    Console.WriteLine("Method2 : " + (a * b));
    return "" + (a * b);
}
Note: For a delegate with a return value, the return value after the last method is executed will be returned.

Action delegation and Func delegation

Both delegates are built-in delegate types of the system.
Action delegate: the return value is empty, and there are 0-16 parameters as the delegate type of any type of method (function).
Func delegate: returns a value of any type, and has 0-16 parameters as the delegate type of any type of method (function).

class Program
{<!-- -->
    private static void Method1(bool a, string b)
    {<!-- -->
        Console.WriteLine("Method1");
    }

    static void Main(string[] args)
    {<!-- -->
        Action<bool, string> actionDelegate = Method1;
        actionDelegate(true, "a");//Output: Method1

        Func<int, double, Program, object, string> funcDelegate = Method2;
        funcDelegate(1, 2.2f, new Program(), (object)1);//Output: Method2

        Console. ReadLine();
    }

    private static string Method2(int a, double b, Program c, object d)
    {<!-- -->
        Console.WriteLine("Method2");
        return "";
    }
}
Action<bool, string> is a delegate whose first parameter is bool type, second parameter is string type, and returns null.
Func<int, double, Program, object, string> is a delegate whose first parameter is int type, second parameter is double type, third is Program type, fourth is object type, and returns string type.

Anonymous methods and Lambda expressions

For code content that does not need to be written repeatedly, by using anonymous methods or Lambda expressions, it is not necessary to create separate methods, thereby reducing the amount of code writing.

1. Anonymous method

Syntax for anonymous methods

delegate(<function parameter>){function body};

Use of anonymous methods

Action<bool, string> actionDelegate = delegate(bool a, string b)
{<!-- -->
    Console.WriteLine("Method1");
};
actionDelegate(true, "a");//Output: Method1

2. Lambda expression

Syntax of Lambda expressions

Multiple parameters and multiple statements: (<function parameters>) => {function body};
Multiple parameters and one return statement: (<function parameter>) => <return statement>;
Multiple statements for one parameter: <function parameter> => {function body}
One parameter and one return statement: <function parameter> => <return statement>;

Use of Lambda expressions

//Multiple parameters and multiple statements: (<function parameters>) => {function body};
Func<double, bool, int> funcDelegate1 =
(a, b) =>{<!-- -->

    if(b)
    {<!-- -->
        return (int)(a * a);
    }
    return (int)a;

};
Console.WriteLine("funcDelegate1 : " + funcDelegate1(2, true));//Output: funcDelegate1 : 4

//Multiple parameters and one return statement: (<function parameter>) => <return statement>;
Func<int, bool, bool> funcDelegate2 = (a, b) => b;
Console.WriteLine("funcDelegate2 : " + funcDelegate2(2, false));//Output: funcDelegate2 : False

//Multiple statements for one parameter: <function parameter> => {function body}
Action<string> actionDelegate1 = a =>
{<!-- -->
    string tmp = "actionDelegate1" + a;
    Console. WriteLine(tmp);
};
actionDelegate1("function body");//Output: actionDelegate1 function body

//One parameter and one return statement: <function parameter> => <return statement>;
Func<float, float> funcDelegate3 = x => x * x;
Console.WriteLine("funcDelegate3 : " + funcDelegate3(8));//Output: funcDelegate3 : 64

Console. ReadLine();

Event

Events are “restricted” delegates.

declare events

public delegate void WriteDelegate();
//<access modifier> event delegate name event name
public event WriteDelegate WriteEvent;

Use of events

class Student
{<!-- -->
    private string Name {<!-- --> get; set; }
    public Student(string Name)
    {<!-- -->
        this.Name = Name;
    }
    public void StartWriting()
    {<!-- -->
        Console.WriteLine(Name + "Start answering");
    }
}

class teacher
{<!-- -->
    public delegate void WriteDelegate();
    //<access modifier> event delegate name event name
    public event WriteDelegate WriteEvent;

    public void Begin()
    {<!-- -->
        WriteEvent();//raise an event
    }
}
class Program
{<!-- -->
    static void Main(string[] args)
    {<!-- -->
        Teacher teacher = new Teacher();
        Student stu1 = new Student("Zhang San");
        Student stu2 = new Student("Li Si");
        Student stu3 = new Student("Wang Wu");
        Student stu4 = new Student("Liu Liu");

        teacher.WriteEvent += stu1.StartWriting;
        teacher.WriteEvent += stu2.StartWriting;
        teacher.WriteEvent += stu3.StartWriting;
        teacher.WriteEvent += stu4.StartWriting;
        teacher. Begin();
        // output:
        //Zhang San starts answering
        //Li Si starts to answer
        //Wang Wu starts to answer
        //Liu Liu began to answer
        Console. ReadLine();
    }
}

The difference between delegate and event

  1. Events cannot be called externally, but delegates can.
  2. Events cannot be assigned externally using “=”, while delegates can.

Due to the limited energy of the author, some mistakes and omissions will inevitably appear in the article. Experts and netizens are welcome to criticize and correct me.