C# Delegates, chaining

Emanuel Gustafzon - Jun 26 - - Dev Community

An awesome feature of delegates are that you can chain methods together.

This enables you to create an instance of the delegate object and in one call, invoke multiple methods.

I think code below kind of explain itself.


class Program {

  public delegate void mathCalculation(int a, int b);

  public static void addition(int a, int b) {
      Console.WriteLine($"Addition: {a + b}");
  }

  public static void multiply(int a, int b)
  {           
  Console.WriteLine($"Multiplication { a * b}");
  }

  public static void Main (string[] args) {

    mathCalculation add = addition;
    mathCalculation mult = multiply;

    mathCalculation chainMath = add + mult;

    chainMath(10, 20);

    chainMath -= add; 

    chainMath(10, 20);
  }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . .