Introduction to Events in C#
Detailed Explanation with Examples
and Best Practices
What Are Events in 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)
Key Components of Events
• 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 '+='
Delegate – The Method 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)
Event – A Special 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;
Publisher – The Source 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
• }
• }
Subscriber – The Class 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!");
• }
• }
Subscription – Binding Subscriber 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
How It Works Internally (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
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!");
• }
Cont..
Here:
•The button is the publisher
•Your method is the subscriber
•The event click is automatically triggered by the UI framework
Benefits of Events
Benefit Explanation
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
Best Practices
Example with Custom EventArgs
• public class Publisher
• {
• public event EventHandler<MyEventArgs> OnDataProcessed;
• public void ProcessData()
• {
• Console.WriteLine("Processing data...");
• OnDataProcessed?.Invoke(this, new MyEventArgs { Message = "Done!" });
• }
• }
• public class Subscriber
• {
• public void HandleData(object sender, MyEventArgs e)
• {
• Console.WriteLine("Received message: " + e.Message);
• }
• }
Basic Custom Event Example
• public delegate void Notify();
• public event Notify OnNotify;
• public void Trigger() {
• OnNotify?.Invoke();
• }
Full Code Example
• class Publisher {
• public delegate void Notify(string msg);
• public event Notify OnNotify;
• public void DoWork() {
• OnNotify?.Invoke("Hello from Publisher!");
• }
• }
• class Subscriber {
• public void Respond(string msg) {
• Console.WriteLine("Received: " + msg);
• }
• }
Real-World Example: Button Click
• button1.Click += ButtonClicked;
• void ButtonClicked(object sender, EventArgs e)
{
• MessageBox.Show("Button was clicked!");
• }
Built-in Delegates
• Use these instead of creating custom
delegates:
• - EventHandler
• - EventHandler<TEventArgs>
• They follow the pattern: void
MethodName(object sender, EventArgs e)
Using Custom EventArgs
• public class MyEventArgs : EventArgs {
• public string Message { get; set; }
• }
• OnDataProcessed?.Invoke(this, new
MyEventArgs { Message = "Done!" });
Benefits of Using Events
• - Loose coupling between components
• - Multiple listeners for a single event
• - Supports modular and scalable code
• - Publisher does not need to know subscriber
details
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
Summary
• - Events connect 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

Lecture #3.pptx, Programming in Visuals.

  • 1.
    Introduction to Eventsin C# Detailed Explanation with Examples and Best Practices
  • 2.
    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
  • 13.
  • 14.
    Example with CustomEventArgs • public class Publisher • { • public event EventHandler<MyEventArgs> OnDataProcessed; • public void ProcessData() • { • Console.WriteLine("Processing data..."); • OnDataProcessed?.Invoke(this, new MyEventArgs { Message = "Done!" }); • } • } • public class Subscriber • { • public void HandleData(object sender, MyEventArgs e) • { • Console.WriteLine("Received message: " + e.Message); • } • }
  • 15.
    Basic Custom EventExample • public delegate void Notify(); • public event Notify OnNotify; • public void Trigger() { • OnNotify?.Invoke(); • }
  • 16.
    Full Code Example •class Publisher { • public delegate void Notify(string msg); • public event Notify OnNotify; • public void DoWork() { • OnNotify?.Invoke("Hello from Publisher!"); • } • } • class Subscriber { • public void Respond(string msg) { • Console.WriteLine("Received: " + msg); • } • }
  • 17.
    Real-World Example: ButtonClick • button1.Click += ButtonClicked; • void ButtonClicked(object sender, EventArgs e) { • MessageBox.Show("Button was clicked!"); • }
  • 18.
    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