Untitled

 avatar
unknown
plain_text
a year ago
1.3 kB
5
Indexable
using System;

public class EventPublisher
{
    // Step 1: Define an event using the event keyword
    public event EventHandler MyEvent;

    // Step 2: A method to raise the event
    public void RaiseEvent()
    {
        Console.WriteLine("Event raised.");
        // Step 3: Check if there are subscribers (null check)
        if (MyEvent != null)
        {
            // Step 4: Invoke the event, passing 'this' as the sender and EventArgs.Empty as the event arguments
            MyEvent(this, EventArgs.Empty);
        }
    }
}

public class EventSubscriber
{
    public void HandleEvent(object sender, EventArgs e)
    {
        Console.WriteLine("Event handled by EventSubscriber.");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        EventPublisher publisher = new EventPublisher();
        EventSubscriber subscriber = new EventSubscriber();

        // Step 6: Subscribe to the event by attaching an event handler
        publisher.MyEvent += subscriber.HandleEvent;

        // Step 7: Raise the event
        publisher.RaiseEvent();

        // Step 8: Unsubscribe from the event
        publisher.MyEvent -= subscriber.HandleEvent;

        // Attempt to raise the event again
        publisher.RaiseEvent(); // No subscribers, no event handled
    }
}
Editor is loading...