Delegate
Delegate is a special data type in C# used to declare references to functions or methods (Can be understood as a pointer to a function). When assigning a function or method to a delegate, the delegate will point the reference to that function or method. Then instead of calling the function directly, we can use the delegate to call it without knowing the function name. Delegates make calling functions more flexible.
In the example above, instead of calling the MaxNumber function directly to find the largest of the two numbers, we call the delegate variable calculatorDelegate.
Use delegates to call different functions
In the above example, we use the calculator delegate to call the Add method if we assign calculator = new Calculator(Add); Call the Subtract method if we assign calculator = new Calculator(Subtract);.
By using the same delegate to call different functions, we see that calling functions is very flexible and easy.
Use the delegate to create a callback
In the example above, we see that we will declare a callback with delegate delegate void Callback(string message);. When we call the function CallMethodWithCallback we can pass the function as a parameter: CallMethodWithCallback("Hello, world!", DisplayMessage);
The above example will produce the following result:
Use delegates in Lambda Expression
Func<int, int, int> is a delegate of type int with 2 parameters passed in int type.
Last updated