What are "Delegates" in C#?
Nima Owji

Nima Owji @nima_owji

About: Full-Stack web developer. Journalist @ Hackernoon. I write about tech and programming.

Location:
Shiraz, Iran
Joined:
Nov 6, 2020

What are "Delegates" in C#?

Publish Date: Nov 26 '20
12 3

Hello, My name is Nima Owji. I am 14. I am a C# programmer for 3 years. Today, I wanna talk about "Delegates". What are them? Read this article!

Delegates are known by "Function-Pointers" too. You can point to a method by them.

Example

See this example:

public int Sum(int a, int b)
{
   return a + b;
}
Enter fullscreen mode Exit fullscreen mode

This is a simple method that can get the sum of two numbers.
Now we want to use it with a delegate:

public delegate int MyDelegate(int a, int b);
MyDelegate = Sum;
int sum = MyDelegate(5,6) // returns 11
Enter fullscreen mode Exit fullscreen mode

As you can see they are like variables.
Delegates are this:

[Scope] delegate [Return type] [DelegateName]([Input parameters])
Enter fullscreen mode Exit fullscreen mode

You can add many methods to a delegate

You can add as many methods as you want to a delegate. Look at this example:

public void Sum(int a, int b)
{
   Console.WriteLine(a + b);
}

public void Pow(int a, int b)
{
   Console.WriteLine(Math.Pow(a, b));
}

public delegate void MyDelegate(int a, int b);
MyDelegate = Sum;
MeDelegate += Pow;

// Now you can use it
MyDelegate(2,3);

// Console will show you this
5
8
Enter fullscreen mode Exit fullscreen mode

As you can see they are really easy. I hope you enjoyed this. Don't forget to like this article and share it. If you have any questions, ask them in a comment.
Follow me on Twitter @nima_owji too, I will answer all of your questions there.

Thank you!

Comments 3 total

  • Nima Owji
    Nima OwjiNov 26, 2020

    Don't forget to follow me on Twitter!

  • Arooran Thanabalasingam
    Arooran ThanabalasingamNov 26, 2020

    I suggest to enable syntax highligting:
    Add cs after first 3 backticks of code block

    • Nima Owji
      Nima OwjiNov 26, 2020

      I did it, Thanks for your suggestion!

Add comment