Intro to C# Delegates

Intro to C# Delegates

Definition of a Delegate

From the Microsoft Docs

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Explanation based on an Example

Declaring a delegate that accepts a method of following form:

Return Type Parameter
string string name

Let's declare an example delegate.

delegate string SayDelegate(string name);

Two example methods for said delegate.

string SayHello(string name) => $"Hello, {name}.";
string SayBye(string name) => $"Bye, {name}.";

Then select a random one of the two methods.

SayDelegate sayInstance;
if (new Random().Next(0, 2) == 1)
    sayInstance = SayHello;
else
    sayInstance = SayBye;

And invoke it and print the result.

Console.WriteLine(sayInstance("KNIF"));
// or
Console.WriteLine(sayInstance.Invoke("KNIF"));

C++ equivalent to upper example with pointers

string SayHello(string name) {
  return "Hello, " + name;
}
string SayBye(string name) {
  return "Bye, " + name;
}

string (*foo)(string);
foo = &SayHello;

std::cout << foo("KNIF"); << std::endl;

Summary and further Resources

I hope this helps understanding delegates and makes you use them more as they're very useful.

If you want to learn more about delegates check out the official Documentation.

Show Comments