delegates and events be fundamental concepts in C# for implementin' the publish-subscribe model, which be critical for building responsive and event-driven applications. Let me explain these concepts and provide examples of their practical use:
Delegates:
A delegate be a type that represents references to methods with a specific signature. In other words, it be a way to pass around references to functions as if they were objects. Delegates be particularly useful for callback mechanisms and decoupling components in an application.
Practical Use of Delegates:
Here's an example of how delegates can be practically used:
// Define a delegate with a specific signature (matching methods that take an int parameter and return void).
public delegate void MyDelegate(int value);
public class Calculator
{
// Create an instance of the delegate.
public MyDelegate CalculationPerformed;
public int Add(int a, int b)
{
int result = a + b;
// Invoke the delegate to notify subscribers.
CalculationPerformed?.Invoke(result);
return result;
}
}
public class Program
{
public static void Main()
{
Calculator calculator = new Calculator();
// Subscribe to the event using the delegate.
calculator.CalculationPerformed += HandleCalculation;
int sum = calculator.Add(5, 3); // This will trigger the delegate.
Console.WriteLine("Sum: " + sum);
}
// Define a method that matches the delegate signature.
public static void HandleCalculation(int result)
{
Console.WriteLine("Calculation performed. Result: " + result);
}
}
In this example:
We define a custom delegate MyDelegate that represents methods taking an
int parameter and returning void.
The Calculator class has a CalculationPerformed delegate field, which represents an event.
When the Add method is called, it performs the addition and then invokes the
CalculationPerformed delegate to notify subscribers (event handlers) about the result.
The Program class subscribes to the event by adding a method (HandleCalculation) to the delegate. When the calculation is performed, the
HandleCalculation method gets called.
Events:
An event be a special type of delegate that provides more control over how subscribers can add or remove event handlers. Events be used to implement the publisher-subscriber pattern more securely, as they restrict direct access to the delegate.
Practical Use of Events:
Here's an example of using events:
public class StockMarket
{
// Define an event using the EventHandler delegate.
public event EventHandler<StockChangedEventArgs> StockChanged;
private decimal currentPrice = 100.00m;
public void SimulateMarket()
{
// Simulate changes in stock price.
while (true)
{
Thread.Sleep(1000);
decimal newPrice = currentPrice + (decimal)(new Random().NextDouble() * 5 - 2.5);
StockChangedEventArgs args = new StockChangedEventArgs(newPrice);
currentPrice = newPrice;
// Raise the event to notify subscribers.
StockChanged?.Invoke(this, args);
}
}
}
public class StockChangedEventArgs : EventArgs
{
public decimal NewPrice { get; }
public StockChangedEventArgs(decimal newPrice)
{
NewPrice = newPrice;
}
}
public class Program
{
public static void Main()
{
StockMarket market = new StockMarket();
market.StockChanged += HandleStockChange;
Console.WriteLine("Stock Market Simulation: ");
market.SimulateMarket();
}
public static void HandleStockChange(object sender, StockChangedEventArgs e)
{
Console.WriteLine($"Stock price changed to: {e.NewPrice:C}");
}
}
In this example:
We define an event StockChanged using the EventHandler<TEventArgs> delegate. This event notifies subscribers when the stock price changes.
The StockMarket class simulates changes in stock prices and raises the
StockChanged event to notify subscribers.
The StockChangedEventArgs class holds information about the new stock price.
The Program class subscribes to the event by adding the
HandleStockChange method as an event handler. When the stock price changes, the event handler is called.
Delegates and events be essential in C# for building responsive and decoupled applications. They allow different parts of an application to communicate and respond to events without directly depending on each other, promoting loose coupling and maintainability.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
delegates and events be fundamental concepts in C# for implementin' the publish-subscribe model, which be critical for building responsive and event-driven applications. Let me explain these concepts and provide examples of their practical use:
Delegates:
A delegate be a type that represents references to methods with a specific signature. In other words, it be a way to pass around references to functions as if they were objects. Delegates be particularly useful for callback mechanisms and decoupling components in an application.
Practical Use of Delegates:
Here's an example of how delegates can be practically used:
In this example:
Events:
An event be a special type of delegate that provides more control over how subscribers can add or remove event handlers. Events be used to implement the publisher-subscriber pattern more securely, as they restrict direct access to the delegate.
Practical Use of Events:
Here's an example of using events:
In this example:
Delegates and events be essential in C# for building responsive and decoupled applications. They allow different parts of an application to communicate and respond to events without directly depending on each other, promoting loose coupling and maintainability.