What Are Eventsin C#?
• Events in C# are a way for one object
(Publisher) to notify others (Subscribers) that
something has occurred. Commonly used in
•GUI programming (e.g., button clicked)
•File operations (e.g., download complete)
•Game development (e.g., player died)
•Networking (e.g., message received)
3.
Key Components ofEvents
• 1. Delegate – Defines the method signature
• 2. Event – A special delegate with restricted
access
• 3. Publisher – The class that raises the event
• 4. Subscriber – The class that handles the
event
• 5. Subscription – Binding the handler to the
event using '+='
4.
Delegate – TheMethod Signature Blueprint
• A delegate defines the type of method that
can handle the event
• public delegate void Notify(); // No return, no
parameter
• You can also use built-in delegates like:
• public event EventHandler MyEvent; //
Standard signature: (object sender, EventArgs
e)
5.
Event – ASpecial Delegate with Controlled
Access
• An event is a wrapper around a delegate,
adding safety so only the declaring class
(publisher) can raise it
• public event Notify OnNotify;
6.
Publisher – TheSource That Raises the Event
• This is the class where the event is defined and triggered
• public class Publisher
• {
• public event Notify OnNotify;
• public void DoWork()
• {
• Console.WriteLine("Working...");
• OnNotify?.Invoke(); // Safely trigger the event
• }
• }
7.
Subscriber – TheClass That Reacts to the
Event
• Any class can subscribe to an event and define how to
react to it.
• public class Subscriber
• {
• public void ShowMessage()
• {
• Console.WriteLine("Event received by subscriber!");
• }
• }
8.
Subscription – BindingSubscriber to
Publisher’s Event
• Publisher pub = new Publisher();
• Subscriber sub = new Subscriber();
• pub.OnNotify += sub.ShowMessage; //
Subscribing
• pub.DoWork(); // Will trigger the subscriber’s
method
9.
How It WorksInternally (Step-by-Step)
•Declare a delegate to describe the handler signature.
•Declare an event using that delegate type.
•Create one or more methods that match the delegate signature.
•Subscribe those methods to the event using +=.
•Trigger the event using .Invoke() or safe-call (?.Invoke()).
•All subscribed methods are called in order
10.
Real-World Example –Button Click Event
• Imagine a button on a form
• button1.Click += ButtonClicked;
• void ButtonClicked(object sender, EventArgs e)
• {
• MessageBox.Show("You clicked the
button!");
• }
11.
Cont..
Here:
•The button isthe publisher
•Your method is the subscriber
•The event click is automatically triggered by the UI framework
12.
Benefits of Events
BenefitExplanation
Loose Coupling The publisher doesn’t need to know who
is listening
Multiple Subscribers
Many classes can respond to the same
event
Decoupled Design Promotes modular, maintainable code
Encapsulation Only the publisher can raise the event
Built-in Delegates
• Usethese instead of creating custom
delegates:
• - EventHandler
• - EventHandler<TEventArgs>
• They follow the pattern: void
MethodName(object sender, EventArgs e)
19.
Using Custom EventArgs
•public class MyEventArgs : EventArgs {
• public string Message { get; set; }
• }
• OnDataProcessed?.Invoke(this, new
MyEventArgs { Message = "Done!" });
20.
Benefits of UsingEvents
• - Loose coupling between components
• - Multiple listeners for a single event
• - Supports modular and scalable code
• - Publisher does not need to know subscriber
details
21.
Best Practices
• -Prefer built-in delegates (EventHandler,
EventHandler<T>)
• - Use ?.Invoke() to prevent null exceptions
• - Unsubscribe when no longer needed
• - Use EventArgs to pass additional data
22.
Summary
• - Eventsconnect publishers and subscribers
• - Delegates define what type of methods can
be called
• - Events are widely used in .NET for UI, async,
and real-time programming
• - Follow safe and clean event handling
practices