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.
// 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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?