Learn about Delegates in C#

Tram Ho

Hi guys, I wish you a productive and energetic day at the beginning of the week. Today I will introduce delegates in C#, a fairly popular feature. Don’t let you wait long, let’s start with the article. In this article, I will talk about the definition, usage and simple example of delegate in c#.

1. What is 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 a reference to that function or method. Then instead of calling the function directly, we can use the delegate to call it without knowing the name of the function. Delegates make calling functions more flexible.

  • In the above example, instead of directly calling the MaxNumber function to find the largest of two numbers, we call the delegate variable calculatorDelegate.

2. Use delegates to call different functions

  • In the above example, we use the delegate calculator 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 find calling the function very flexible and easy.

3. Use a delegate to create a callback

  • In the above example, we see that we will declare a callback with the delegate delegate void Callback(string message);. When we call the function CallMethodWithCallback we can pass the function as an argument: CallMethodWithCallback(“Hello, world!”, DisplayMessage);
  • The above example will output:

4. Using delegates in Lambda Expression

  • Func<int, int, int> is a delegate of type int with two arguments of type int.

5. Summary

  • There are many ways to use delegates in c#, here I just introduce the concept and simple examples so that you can understand what a delegate is and how to use it simply.
  • Thank you to everyone who viewed the article. Have a nice weekend everyone.
  • If you have any questions about the parts of this article, you can inbox via facebook: https://www.facebook.com/FriendsCode-108096425243996 I will answer questions within my understanding. Thanks everyone!
  • Or contact me via my personal facebook: https://www.facebook.com/Flamesofwars/

6. Reference:

Share the news now

Source : Viblo