Medium csharp

Delegate — math operations

Problem

Use a delegate to invoke add or multiply functions.

Hints
  • Declare delegate, assign method, invoke

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

delegate int MathOp(int a, int b);
class Program {
    static int Add(int a, int b) => a + b;
    static int Mul(int a, int b) => a * b;
    static void Main() {
        MathOp op = Add;
        Console.WriteLine(op(3, 4));
        op = Mul;
        Console.WriteLine(op(3, 4));
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Delegates are foundation for events and LINQ—expect follow-ups on Func/Action.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details