DEV Community

Nima Owji
Nima Owji

Posted on

What are "Delegates" in C#?

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!

Top comments (3)

Collapse
 
bigaru profile image
Arooran Thanabalasingam

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

Collapse
 
nima_owji profile image
Nima Owji

I did it, Thanks for your suggestion!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.