0
0
C Sharp (C#)programming~5 mins

Why delegates are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Delegates let you store and use methods like variables. This helps you call different methods flexibly without changing your code.

When you want to pass a method as a parameter to another method.
When you want to decide which method to call at runtime.
When you want to implement event handling in your program.
When you want to write reusable and flexible code that can work with different methods.
When you want to create callback methods that run after some task finishes.
Syntax
C Sharp (C#)
delegate returnType DelegateName(parameterList);
A delegate defines a type that can hold references to methods with a specific signature.
You create delegate instances by assigning methods that match the delegate's signature.
Examples
Defines a delegate named SimpleDelegate that points to methods with no parameters and no return value.
C Sharp (C#)
delegate void SimpleDelegate();
Defines a delegate named MathOperation for methods that take two integers and return an integer.
C Sharp (C#)
delegate int MathOperation(int x, int y);
Sample Program

This program shows how delegates let you choose which method to call at runtime. We define a delegate MathOperation, then assign it to Add and Multiply methods. Calling the delegate runs the assigned method.

C Sharp (C#)
using System;

class Program
{
    // Define a delegate that takes two ints and returns an int
    delegate int MathOperation(int a, int b);

    static int Add(int x, int y) => x + y;
    static int Multiply(int x, int y) => x * y;

    static void Main()
    {
        // Create delegate instances
        MathOperation op = Add;
        Console.WriteLine("Add: " + op(3, 4));

        op = Multiply;
        Console.WriteLine("Multiply: " + op(3, 4));
    }
}
OutputSuccess
Important Notes

Delegates are type-safe, meaning they only point to methods with matching signatures.

They are the foundation for events and callbacks in C#.

Summary

Delegates let you treat methods like variables for flexible code.

They help call different methods without changing the calling code.

Delegates are key for events and callbacks in C#.