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

Delegates as callback pattern in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Delegates let you pass methods as parameters so you can call them later. This helps you run different code when something happens, like a callback.
When you want to run a method after another method finishes.
When you want to customize behavior without changing the original method.
When you want to notify other parts of your program about an event.
When you want to pass different actions to a method to run later.
When you want to keep your code flexible and reusable.
Syntax
C Sharp (C#)
delegate ReturnType DelegateName(ParameterList);

// Example:
delegate void Callback(string message);
A delegate defines a type that can hold references to methods with a matching signature.
You can use delegates to call methods indirectly, enabling callback behavior.
Examples
Defines a delegate with no parameters and calls it inside another method.
C Sharp (C#)
delegate void SimpleCallback();

void Run(SimpleCallback callback) {
    callback();
}

Run(() => Console.WriteLine("Hello!"));
Delegate with a string parameter used to send a message back.
C Sharp (C#)
delegate void MessageCallback(string msg);

void ShowMessage(MessageCallback callback) {
    callback("Hi there!");
}

ShowMessage(msg => Console.WriteLine(msg));
Sample Program
This program shows how to use a delegate as a callback. The ProcessData method does some work and then calls the callback to notify about completion.
C Sharp (C#)
using System;

class Program {
    // Define a delegate type that takes a string and returns void
    delegate void Notify(string message);

    // Method that accepts a delegate as a callback
    static void ProcessData(Notify callback) {
        Console.WriteLine("Processing data...");
        // After processing, call the callback
        callback("Data processed successfully.");
    }

    static void Main() {
        // Call ProcessData and pass a method as callback
        ProcessData(PrintNotification);

        // Or use a lambda expression as callback
        ProcessData(msg => Console.WriteLine($"Lambda says: {msg}"));
    }

    static void PrintNotification(string message) {
        Console.WriteLine("Notification: " + message);
    }
}
OutputSuccess
Important Notes
Delegates can point to any method with the same signature, making callbacks flexible.
You can use lambda expressions to write inline callbacks without defining separate methods.
Delegates help keep your code clean by separating the action from the method doing the work.
Summary
Delegates let you pass methods as parameters to other methods.
This pattern is useful for callbacks to run code after some work is done.
You can use named methods or lambda expressions as callbacks.