What are delegates and events

Delegates and events are essential components of the C# programming language, allowing for a more event-driven programming style. A delegate is a type that represents references to methods with a specific parameter list and return type. Events are built on top of delegates, providing a way for a class to notify other classes or objects when something of interest occurs.

Delegates can be thought of as type-safe function pointers, enabling methods to be passed as parameters. Events use delegates to provide notification capabilities to subscribers when an event occurs.

Example of Delegate and Event

// Define a delegate public delegate void Notify(); // Define a class that uses the delegate public class ProcessBusinessLogic { // Declare the event using the delegate public event Notify ProcessCompleted; public void StartProcess() { // Some process logic here Console.WriteLine("Process Started!"); // Raise the event OnProcessCompleted(); } protected virtual void OnProcessCompleted() { ProcessCompleted?.Invoke(); } } // Subscriber class public class Subscriber { public void Subscribe(ProcessBusinessLogic process) { process.ProcessCompleted += ProcessCompletedHandler; } private void ProcessCompletedHandler() { Console.WriteLine("Process Completed!"); } } // Main program public class Program { static void Main(string[] args) { ProcessBusinessLogic process = new ProcessBusinessLogic(); Subscriber subscriber = new Subscriber(); subscriber.Subscribe(process); process.StartProcess(); } }

delegates events C# programming event-driven method references notifications