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

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay