csharp-delegados

What are and how to use delegates in C#

  • 7 min

A delegate is a type that represents a reference to a function or method. Delegates allow methods to be passed as parameters, assigned to variables, and executed dynamically at runtime.

To do this, the delegate must match the signature (parameters received) of the function, and its specific return type.

In simple terms, a delegate can be thought of as a kind of function pointer, but with the safety and robustness of C#‘s type system.

If you want to learn more, check out the Introduction to Programming Course

Declaring a delegate

To declare a delegate in C# the delegate keyword is used, followed by the signature of the method the delegate will represent.

delegate ReturnType MyDelegate(ParameterType parameter1...);
Copied!
  • ReturnType, the return type of the function we want to delegate
  • Type parameter…, the parameters of the function we want to delegate

For example, if we want to declare a delegate that represents a method that returns no value and takes two integer parameters, the declaration would look like this:

Basic example

For example, if we wanted to define a delegate that can point to any function that takes a string as a parameter and returns no value (void), we could do it like this:

public delegate void MyDelegate(string message);
Copied!

And if we want to declare a delegate that references a function that takes two int parameters and returns a double, the declaration would look like this:

delegate void MyDelegate(int parameter1, int parameter2);
Copied!

Using delegates

Once the delegate is declared, we can create an instance of the delegate and assign it a method that matches its signature.

To do this, we can create it using its constructor

MyDelegate delegate = new MyDelegate(ReferencedFunction);
Copied!

Or simply assign it

MyDelegate delegate = ReferencedFunction;
Copied!

Let’s see it with an example. Suppose we have the function ShowMessage(string ...).

// Method we want to reference
public static void ShowMessage(string message)
{
	Console.WriteLine("Delegate: " + message);
}

// Delegate definition
public delegate void MyDelegate(string message);

public static void Main(string[] args)
{
	// Now we create a MyDelegate that points to ShowMessage
	MyDelegate delegate = ShowMessage;
}
Copied!

Here we have,

  • Defined a delegate MyDelegate, which matches the form of ShowMessage.
  • Created a new instance of MyDelegate, called delegate
  • Assigned the instance delegate to ShowMessage.

Invoking a delegate

Once we have defined the delegate, created a delegate, and referenced a function with it, we can invoke it simply by doing () as we would with the original function.

In the previous example, we could invoke delegate simply like this.

// Invoking the method through the delegate
delegate("Hello, World!");
}
Copied!

So it would be displayed on screen

Delegate: Hello, World!
Copied!

Generic delegates: Func and Action

To simplify the use of delegates, C# provides predefined generic delegates.

The most common ones are Action and Func.

  • Action: Represents a method that does not return a value
  • Func<TResult>: Represents a method that returns a value of type TResult

Using Action

Action<string> show = message => Console.WriteLine(message);

show("Hello with Action!");
Copied!

Using Func

Func<int, int, int> add = (a, b) => a + b;
int result = add(3, 4);

Console.WriteLine("Result of the addition: " + result);
Copied!

In general, this form is what you will normally use, as opposed to defining the delegate explicitly. Especially if it’s a temporary use, not worth defining in the traditional way.

Multicast Delegates

A Multicast delegate is a delegate that can have more than one method in its invocation. In reality, all C# delegates are Multicast.

If you want to know more, check out this entry

Using delegates with events

Delegates are the foundation of events in C#. An event is a notification sent by an object to signal the occurrence of an action. Delegates allow subscribing methods that will be called when the event is fired.

If you want to know more, check out this entry

Practical examples