C# delegates

C# delegates

What is a delegate?

a delegate is a reference type variable that holds the reference of a method. C# delegates are similar to the C / C++ equivalent of pointers to the method - a delegate holds the address of a method that can be called using the delegate.

A delegate is an object that knows how to call a method.

Defining the delegate

A delegate type defines the kind of method that delegate instances can call. Specifically, it defines the method’s return type and its parameter types. The following defines a delegate type called Transformer:

delegate int Transformer (int x);

above delegate Transformer is compatible with any method with an int return type and a single int parameter. for example

    int Square (int x) { return x * x; }
    // OR
    int Square (int x) => x * x;

assigning a method to a delegate variable creates a delegate instance. a delegate instance can be invoked in the same way as a method.

Transformer t = Square;
int answer = t(3);  // 9
//OR 
int answer = t.Invoke(3); // 9

// t(3) is shorthand for t.Invoke(3)
💡
A delegate instance acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method
  • Delegates are used to define callback methods and implement event handling.

  • Delegates allow methods to be passed as parameters.

  • Delegates can be chained together; for example, multiple methods can be called on a single event (multicast delegates).

Multicast delegates

all delegates have multicast ability which means a delegate instance can reference more than one method.

SomeDelegate d = SomeMethod1;
d += SomeMethod2;
  • multicast delegates are invoked in the order in which they are added.

  • a method could be removed at runtime from the multicast delegate.

    d -= SomeMethod1;

  • If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. for most of the scenarios where multicast delegates are used, methods have a void return type.

Generic delegate types

A delegate type can have generic type parameters and return type :

public delegate T Transformer<T> (T arg);
int[] values = { 1, 2, 3 };
Util.Transform (values, Square); // Hook in Square
foreach (int i in values)
  Console.Write (i + " "); // 1 4 9
int Square (int x) => x * x;
public class Util {
 public static void Transform<T> (T[] values, Transformer<T> t) {
   for (int i = 0; i < values.Length; i++)
     values[i] = t (values[i]);
 }
}

The Func and Action Delegates

both Func and Action delegates are reference types that encapsulate a method.

The Func delegate refers to a method that accepts some parameters and returns a value.

The Action delegate refers to a method that accepts parameters but do not return any value.

below is the declaration syntax of a Func delegate :

Func<in_param 1, in_param 2, out_Param > name ;

      static void Main(string[] args) {
         Func<string, string, string> func = Concat;
         string fullName = func("Deepak", "Jain");
         Console.WriteLine(fullName);
         Console.ReadLine();
      }
      static string Concat (string firstName, string lastName) {
         return firstName + lastName;
      }

Below is an example of Action delegate :

Action<in_param> name

static void Main(string[] args) {
         Action<string> act = Display;
         act("Hello World"); // Hello World
         Console.ReadLine();
      }
      static Display (string content) {
         console.log(content);
      }

That's it for this article, please share your feedback in comment section.

references and further reading

Did you find this article valuable?

Support Deepak Kumar Jain by becoming a sponsor. Any amount is appreciated!