public class MyPublisher : IEventPublisher { public event EventHandlerMyEvent; public void Publish(MyEventArgs args) { MyEvent?.Invoke(this, args); } } public class MySubscriber { public MySubscriber(IEventPublisher publisher) { publisher.MyEvent += HandleEvent; } private void HandleEvent(object sender, MyEventArgs args) { Console.WriteLine($"Received event: {args.Message}"); } } public class MyEventArgs : EventArgs { public string Message { get; set; } } // Usage: MyPublisher publisher = new MyPublisher(); MySubscriber subscriber = new MySubscriber(publisher); publisher.Publish(new MyEventArgs { Message = "Hello, world!" });
public class MyPublisher : IEventPublisher { public event EventHandler MyEvent; public void Publish() { MyEvent?.Invoke(this, EventArgs.Empty); } } public class MySubscriber { public MySubscriber(IEventPublisher publisher) { publisher.MyEvent += HandleEvent; } private void HandleEvent(object sender, EventArgs args) { Console.WriteLine("Received event!"); } } // Usage: MyPublisher publisher = new MyPublisher(); MySubscriber subscriber = new MySubscriber(publisher); publisher.Publish();This example is a simpler version of the previous example, where the event arguments are not needed. The MyPublisher class raises the MyEvent event with no arguments, and the MySubscriber class handles the event by simply writing out a message to the console. Package library: The System namespace included in .NET Framework.