DEV Community

aliona matveeva
aliona matveeva

Posted on

One Minute Notes: delegates in C#

I am staring a new section in my blog — the One Minute Notes, short notes on some important IT topics that will take only one minute to read and get a brief understanding of the concept. In this episode of One Minute Notes, let’s talk about what are delegates in C# and why do we need them.

Delegates might be considered as placeholders for functions that can be called later. Just like declaring a variable to store some integer value, you can declare a variable to store a function as a value, which allows you to change the function to be called in the runtime.

Here’s an example of defining and using a delegate. Of course, this is the most naive implementation. A real-life example would probably contain an if-clause or switch to choose between functions to delegate based on some condition.

public delegate int BinaryOperation(int a, int b);

class SampleClass
{
  public static int Add(int a, int b)
  {
     return a + b;
  }

  static int Subtract(int a, int b) => a - b;

  static void Main(string[] args)
  {
    BinaryOperation operation = Subtract;
    int x = operation (10, 2); // 8

    operation = Add;
    int x = operation(10, 2); // 12
  }
}
Enter fullscreen mode Exit fullscreen mode

Fun fact: .NET Base Class Library also has its own predefined delegates that cover most popular use-cases, so it’s usually unnecessary to implement delegates of your own. The Action delegate represents a void function, which might take a parameter(s) with generic type. For example, Action<string> printText = x => Console.WriteLine(x); There’s also a Func delegate which defines functions that return a value. Overall, it has the same signature, but the last parameter defines the return value type. In the example above, the Add function might also be assigned to the Func<int, int, int> delegate.


Did you find this One Minute Note helpful? Hit like and follow me to read more of them later🙂

Top comments (2)

Collapse
 
nnhao profile image
Nguyen Nhut Hao • Edited

I know C# and meet the delegate 2 years ago, but this is the first time I can feel and understand it. Very clear and shortly explained.

Collapse
 
yellalena profile image
aliona matveeva

thank you! I appreciate the feedback 💙