Multi-cast delegates in C# allow multiple methods to be invoked in sequence through a single delegate. This guide will introduce multi-cast delegates, walk through defining and using them, and explore their practical use cases, followed by a real-world example and a summary of key points.
A multi-cast delegate in C# can hold references to more than one method, allowing you to invoke a series of methods with a single delegate instance. These delegates are commonly used when an action needs to trigger several responses, such as notifying multiple components or processing tasks in a sequence. By chaining methods in one delegate, multi-cast delegates streamline code organization and improve modularity.
Multi-cast delegates are defined like any other delegate. They can be instantiated by assigning multiple methods to a single delegate instance using the +
operator (or +=
shorthand).
public delegate ReturnType DelegateName(ParameterList);
using System;
// Define a delegate type
public delegate void NotificationDelegate(string message);
class Program
{
// Methods that match the delegate signature
static void NotifyByEmail(string message)
{
Console.WriteLine("Email Notification: " + message);
}
static void NotifyBySMS(string message)
{
Console.WriteLine("SMS Notification: " + message);
}
static void Main()
{
// Instantiate a multi-cast delegate by adding methods
NotificationDelegate notify = NotifyByEmail;
notify += NotifyBySMS;
// Invoke the delegate
notify("Your order has been shipped.");
}
}
NotificationDelegate
: A delegate type that can reference any method with a void
return type and a single string
parameter.NotifyByEmail
and NotifyBySMS
: Methods that match the delegate’s signature, which allows both to be invoked through the delegate instance.NotifyByEmail
and then NotifyBySMS
when invoked.Use Case: This example is helpful in notification systems where multiple methods, such as email and SMS, are triggered by a single event.
Consider a scenario where we have an application that needs to log and notify users when an error occurs. A multi-cast delegate can simplify calling different response methods for error handling.
using System;
// Define a delegate for handling errors
public delegate void ErrorHandlerDelegate(string error);
class ErrorLogger
{
public static void LogErrorToDatabase(string error)
{
Console.WriteLine("Database Log: " + error);
}
public static void LogErrorToFile(string error)
{
Console.WriteLine("File Log: " + error);
}
}
class ErrorNotifier
{
public static void NotifyAdmin(string error)
{
Console.WriteLine("Admin Notification: " + error);
}
}
class Program
{
static void Main()
{
// Create a multi-cast delegate instance
ErrorHandlerDelegate errorHandler = ErrorLogger.LogErrorToDatabase;
errorHandler += ErrorLogger.LogErrorToFile;
errorHandler += ErrorNotifier.NotifyAdmin;
// Invoke the delegate to handle an error
errorHandler("An unexpected error occurred in the application.");
}
}
ErrorHandlerDelegate
: A delegate type that handles error messages, referencing methods with a string
parameter.errorHandler
triggers all three methods, simplifying error handling code.Use Case: This pattern is particularly useful in logging and notification systems where multiple responses are required for the same event, like logging errors to different sources and notifying administrators.
Multi-cast delegates are often used in applications that require notifying multiple observers of a single event. For instance, consider an event notification system in a stock trading application where multiple modules need to react to a price update.
using System;
public delegate void PriceUpdateDelegate(decimal newPrice);
class PriceNotifier
{
public static void UpdateTraderUI(decimal newPrice)
{
Console.WriteLine("Trader UI Updated with New Price: $" + newPrice);
}
public static void LogPriceChange(decimal newPrice)
{
Console.WriteLine("Price Change Logged: $" + newPrice);
}
public static void NotifyInvestors(decimal newPrice)
{
Console.WriteLine("Investor Notification Sent: $" + newPrice);
}
}
class Program
{
static void Main()
{
// Multi-cast delegate for price update event
PriceUpdateDelegate priceUpdate = PriceNotifier.UpdateTraderUI;
priceUpdate += PriceNotifier.LogPriceChange;
priceUpdate += PriceNotifier.NotifyInvestors;
// Simulate price update
priceUpdate(102.50M);
}
}
PriceUpdateDelegate
: A delegate type for price update notifications, referencing methods with a decimal
parameter.UpdateTraderUI
, LogPriceChange
, and NotifyInvestors
, all responding to a price update event.Real-World Use Case: Event notification systems in financial or IoT applications benefit from multi-cast delegates by handling multiple responses to a single event, like notifying users, updating displays, and logging.
Multi-cast delegates in C# offer an elegant solution for invoking multiple methods in response to a single event. Their ability to chain methods enhances flexibility and modularity in applications, especially those requiring multiple responses to events, like logging, notifications, or updating different components. Whether it’s notifying multiple parties of a change or logging to various sources, multi-cast delegates help maintain clean and organized code in event-driven applications.