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

Delegate declaration and instantiation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Delegates let you store references to methods. This helps you call methods indirectly and pass them around like variables.

When you want to call different methods using the same variable.
When you want to pass a method as a parameter to another method.
When you want to define callback methods for events.
When you want to create flexible and reusable code that can change behavior at runtime.
Syntax
C Sharp (C#)
delegate return_type DelegateName(parameter_list);

DelegateName delegateInstance = new DelegateName(MethodName);

The delegate keyword declares a delegate type.

Delegate instances are created by passing a method name matching the delegate signature.

Examples
This declares a delegate that points to methods with no parameters and no return value. Then it creates an instance pointing to SayHello.
C Sharp (C#)
delegate void SimpleDelegate();

void SayHello() {
    Console.WriteLine("Hello!");
}

SimpleDelegate d = new SimpleDelegate(SayHello);
This delegate points to methods taking two integers and returning an integer. It is assigned to the Add method.
C Sharp (C#)
delegate int MathOperation(int x, int y);

int Add(int x, int y) {
    return x + y;
}

MathOperation op = new MathOperation(Add);
Sample Program

This program declares a delegate GreetDelegate for methods that take a string and return nothing. It creates instances pointing to two different greeting methods and calls them.

C Sharp (C#)
using System;

class Program {
    delegate void GreetDelegate(string name);

    static void GreetMorning(string name) {
        Console.WriteLine($"Good morning, {name}!");
    }

    static void GreetEvening(string name) {
        Console.WriteLine($"Good evening, {name}!");
    }

    static void Main() {
        GreetDelegate greet = new GreetDelegate(GreetMorning);
        greet("Alice");

        greet = new GreetDelegate(GreetEvening);
        greet("Bob");
    }
}
OutputSuccess
Important Notes

Delegate method signatures must match exactly (parameters and return type).

You can use shorthand syntax: GreetDelegate greet = GreetMorning; without new.

Delegates can point to multiple methods using multicast, but that is an advanced topic.

Summary

Delegates hold references to methods with a specific signature.

Declare delegates with the delegate keyword and instantiate by passing a method name.

Delegates enable flexible and reusable code by allowing methods to be passed and called indirectly.