In C#, events are utilized to pass data using EventArgs.

In C#, data can be passed through events, with the EventArgs class used to encapsulate event parameters. Below is a simple example:

First, define a class that contains events.

public class DataEventArgs : EventArgs
{
    public string Data { get; set; }

    public DataEventArgs(string data)
    {
        Data = data;
    }
}

public class DataPublisher
{
    public event EventHandler<DataEventArgs> DataPublished;

    public void PublishData(string data)
    {
        OnDataPublished(new DataEventArgs(data));
    }

    protected virtual void OnDataPublished(DataEventArgs e)
    {
        DataPublished?.Invoke(this, e);
    }
}

Next, create a subscriber class to handle events.

public class DataSubscriber
{
    public void Subscribe(DataPublisher publisher)
    {
        publisher.DataPublished += Publisher_DataPublished;
    }

    private void Publisher_DataPublished(object sender, DataEventArgs e)
    {
        Console.WriteLine("Received data: " + e.Data);
    }
}

Finally, use these classes in the main program.

public class Program
{
    public static void Main(string[] args)
    {
        DataPublisher publisher = new DataPublisher();
        DataSubscriber subscriber = new DataSubscriber();
        subscriber.Subscribe(publisher);

        publisher.PublishData("Hello, World!");

        Console.ReadLine();
    }
}

When publisher.PublishData(“Hello, World!”) is called, the event will be triggered, and then the Publisher_DataPublished method in the subscriber class will be executed, printing out the received data.

bannerAds