Events help programs respond to actions or changes automatically. They let parts of a program talk to each other without being tightly connected.
When a button is clicked in a user interface and you want to run some code.
When a file finishes downloading and you want to start processing it.
When a sensor detects a change and you want to update the display.
When a timer reaches zero and you want to trigger an alert.
Syntax
C Sharp (C#)
public event EventHandler EventName;
// To raise the event:
EventName?.Invoke(this, EventArgs.Empty);
Events are declared with the event keyword.
They use delegates to define the method signature for event handlers.
Examples
This example shows a simple event named Clicked that can be triggered.
C Sharp (C#)
public event EventHandler Clicked;
// Raise the event
Clicked?.Invoke(this, EventArgs.Empty);
Here, a custom delegate is used to define the event's method signature.
C Sharp (C#)
public delegate void ThresholdReachedEventHandler(object sender, EventArgs e);
public event ThresholdReachedEventHandler ThresholdReached;
Sample Program
This program creates a button that raises an event when pressed. The main program listens to the event and responds by printing a message.
C Sharp (C#)
using System;
class Button
{
public event EventHandler Clicked;
publicvoid Press()
{
Console.WriteLine("Button was pressed.");
Clicked?.Invoke(this, EventArgs.Empty);
}
}
class Program
{
staticvoid Main()
{
Button button = new Button();
button.Clicked += Button_Clicked;
button.Press();
}
privatestaticvoid Button_Clicked(object sender, EventArgs e)
{
Console.WriteLine("Event handler: Button was clicked!");
}
}
OutputSuccess
Important Notes
Events help keep code organized by separating the action from the response.
Using events makes programs easier to maintain and extend.
Summary
Events allow parts of a program to communicate without tight connections.
They are useful for responding to user actions or changes automatically.
Events improve code organization and flexibility.
Practice
(1/5)
1. Why are events needed in C# programming?
easy
A. To allow different parts of a program to communicate without being tightly connected
B. To make the program run faster by using multiple threads
C. To store data permanently on disk
D. To create user interfaces with buttons and text boxes
Solution
Step 1: Understand the purpose of events
Events let different parts of a program talk to each other without needing to know details about each other.
Step 2: Compare with other options
Options B, C, and D describe other programming tasks but not the main reason for events.
Final Answer:
To allow different parts of a program to communicate without being tightly connected -> Option A
Quick Check:
Events enable loose communication = A [OK]
Hint: Events connect parts without tight links [OK]
Common Mistakes:
Confusing events with threading
Thinking events store data
Assuming events create UI elements
2. Which of the following is the correct way to declare an event in C#?
easy
A. public event EventHandler MyEvent;
B. public void event MyEvent();
C. event public MyEvent EventHandler;
D. public EventHandler event MyEvent;
Solution
Step 1: Recall C# event declaration syntax
Events are declared with the keyword 'event' followed by the delegate type and event name.
Step 2: Check each option
public event EventHandler MyEvent; matches the correct syntax. Options A, C, and D have incorrect order or keywords.
Final Answer:
public event EventHandler MyEvent; -> Option A
Quick Check:
Correct event syntax = B [OK]
Hint: Use 'public event DelegateType EventName;' [OK]
Common Mistakes:
Placing 'event' after the delegate type
Using 'void' with event keyword
Mixing order of keywords
3. What will be the output of this C# code?
using System;
class Program {
public static event Action OnChange;
static void Main() {
OnChange += () => Console.WriteLine("Event triggered");
OnChange?.Invoke();
}
}
medium
A. No output
B. Runtime error
C. Compilation error
D. Event triggered
Solution
Step 1: Understand event subscription and invocation
The event OnChange is subscribed with a lambda that prints "Event triggered". Then it is invoked safely with ?.Invoke().
Step 2: Predict the output
Since the event has a subscriber, invoking it prints "Event triggered" to the console.
Final Answer:
Event triggered -> Option D
Quick Check:
Subscribed event invoked prints message = D [OK]
Hint: Subscribed event prints message when invoked [OK]
Common Mistakes:
Forgetting to subscribe before invoking
Not using null-conditional operator causing errors
Expecting no output without subscription
4. Identify the error in this C# event usage:
class MyClass {
public event Action OnUpdate;
public void Update() {
OnUpdate();
}
}
medium
A. Event OnUpdate is not subscribed before invocation
B. Event OnUpdate cannot be invoked directly without null check
C. Event OnUpdate should be declared as static
D. Event OnUpdate must return a value
Solution
Step 1: Check event invocation safety
Invoking an event directly without checking if it has subscribers can cause a NullReferenceException.
Step 2: Identify the fix
Use null-conditional operator or check if OnUpdate is not null before invoking.
Final Answer:
Event OnUpdate cannot be invoked directly without null check -> Option B
Quick Check:
Always check event is not null before invoking = A [OK]
Hint: Check event is not null before calling [OK]
Common Mistakes:
Invoking event without null check
Assuming events are static by default
Expecting events to return values
5. You want to design a program where multiple parts react automatically when a data value changes. Why should you use events instead of calling methods directly?
hard
A. Events store the data changes permanently
B. Events make the program run faster by parallel processing
C. Events allow adding or removing reactions without changing the data code
D. Events prevent any part from reacting to changes
Solution
Step 1: Understand flexibility of events
Events let you add or remove listeners easily without changing the code that changes data.
Step 2: Compare with other options
Options A, B, and D describe unrelated or incorrect behaviors.
Final Answer:
Events allow adding or removing reactions without changing the data code -> Option C
Quick Check:
Events improve flexibility and decoupling = C [OK]