DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

C# Delegates, chaining

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

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

This is mistagged. #c is the tag for C. You want #csharp.

Collapse
 
emanuelgustafzon profile image
Emanuel Gustafzon

Thanks for the observation! Iโ€™ll change it ๐Ÿ˜€