DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

2

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 πŸ˜€

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more