To create generic delegates and use them for eventhandling in C#, you can follow these steps:
Step 1: Define a generic delegate.
public delegate void GenericEventHandler<T>(T data);
Step 2: Create an event using the generic delegate.
public class EventPublisher
{
public event GenericEventHandler<string> StringEvent;
public event GenericEventHandler<int> IntEvent;
}
Step 3: Publish events.
public class EventPublisher
{
public event GenericEventHandler<string> StringEvent;
public event GenericEventHandler<int> IntEvent;
public void PublishStringEvent(string message)
{
StringEvent?.Invoke(message);
}
public void PublishIntEvent(int number)
{
IntEvent?.Invoke(number);
}
}
Step 4: Subscribe to and handle events.
public class EventSubscriber
{
public EventSubscriber(EventPublisher publisher)
{
publisher.StringEvent += HandleStringEvent;
publisher.IntEvent += HandleIntEvent;
}
public void HandleStringEvent(string message)
{
Console.WriteLine($"Received string event: {message}");
}
public void HandleIntEvent(int number)
{
Console.WriteLine($"Received int event: {number}");
}
}
Now you can create an instance of EventPublisher and
EventSubscriber to demonstrate the use of generic delegates for event handling. This allows you to handle events with different data types using the same delegate.
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.
To create generic delegates and use them for event handling in C#, you can follow these steps:
Step 1: Define a generic delegate.
Step 2: Create an event using the generic delegate.
Step 3: Publish events.
Step 4: Subscribe to and handle events.
Now you can create an instance of EventPublisher and EventSubscriber to demonstrate the use of generic delegates for event handling. This allows you to handle events with different data types using the same delegate.