---
title: "How to create generic delegates and use them in event handling?"  
description: "How to create generic delegates and use them in event handling?"  
author: "Steilla Mitchel"  
published: 2023-11-03  
updated: 2023-11-05  
canonical: https://www.mindstick.com/forum/160402/how-to-create-generic-delegates-and-use-them-in-event-handling  
category: "c#"  
tags: ["c#", "delegates", "generic class"]  
reading_time: 1 minute  

---

# How to create generic delegates and use them in event handling?

How to create generic delegates and use them in [event handling](https://www.mindstick.com/forum/161387/how-does-event-handling-work-in-angularjs)?

## Replies

### Reply by Aryan Kumar

To create generic delegates and use them for [event](https://www.mindstick.com/articles/167719/marquee-hire-benefits-of-event-lighting-hire-london) [handling](https://www.mindstick.com/forum/34585/file-handling) in C#, you can follow these steps:

Step 1: Define a generic delegate.

```plaintext
public delegate void GenericEventHandler<T>(T data);
```

Step 2: Create an event using the generic delegate.

```plaintext
public class EventPublisher
{
    public event GenericEventHandler<string> StringEvent;
    public event GenericEventHandler<int> IntEvent;
}
```

Step 3: Publish events.

```plaintext
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.

```plaintext
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.


---

Original Source: https://www.mindstick.com/forum/160402/how-to-create-generic-delegates-and-use-them-in-event-handling

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
