Delegates and Events are powerful features in C#. They allow you to write flexible and loosely coupled code.
Definition: A delegate is like a pointer to a method. It can reference any method with the same signature and return type.
Use Case: Useful for callbacks and passing methods as parameters.
// Step 1: Define a delegate
delegate void GreetDelegate(string name);
class Program
{
static void Main()
{
// Step 2: Assign a method to delegate
GreetDelegate greeter = SayHello;
// Step 3: Invoke delegate
greeter("Manoj");
}
static void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
Definition: Events are built on top of delegates. They provide a way for a class to notify other classes when something happens.
Use Case: Useful for notification systems (e.g., button click, file download complete).
// Step 1: Define delegate for event
delegate void Notify();
class Process
{
// Step 2: Declare event using delegate
public event Notify ProcessCompleted;
public void StartProcess()
{
Console.WriteLine("Process Started...");
// Do work here...
// Step 3: Raise event
ProcessCompleted?.Invoke();
}
}
class Program
{
static void Main()
{
Process process = new Process();
// Subscribe to event
process.ProcessCompleted += ProcessFinishedHandler;
process.StartProcess();
}
static void ProcessFinishedHandler()
{
Console.WriteLine("Process Finished!");
}
}