What happens if you subscribe to an event but never unsubscribe in C#?
The subscriber object remains referenced by the event publisher, preventing it from being garbage collected. This can cause memory leaks.
Click to reveal answer
beginner
How do you unsubscribe from an event in C#?
Use the '-=' operator with the same event handler method used to subscribe. For example: publisher.EventName -= HandlerMethod;
Click to reveal answer
intermediate
Why is event unsubscription important for memory management?
Because events hold references to subscribers, failing to unsubscribe keeps those subscribers alive in memory, causing leaks and increased memory usage.
Click to reveal answer
intermediate
What is a common pattern to avoid forgetting to unsubscribe from events?
Implement IDisposable in the subscriber and unsubscribe from events in the Dispose method to ensure cleanup.
Click to reveal answer
advanced
Can weak references help with event subscriptions? How?
Yes. Using weak event patterns or weak references allows the subscriber to be garbage collected even if still subscribed, reducing memory leaks.
Click to reveal answer
What operator is used to unsubscribe from an event in C#?
A!=
B+=
C==
D-=
✗ Incorrect
The '-=' operator removes the event handler from the event's invocation list.
What problem can occur if you never unsubscribe from events?
AMemory leaks
BFaster execution
CAutomatic unsubscription
DNo effect
✗ Incorrect
Not unsubscribing keeps references alive, causing memory leaks.
Where is a good place to unsubscribe from events in a subscriber class?
AIn the event publisher
BIn the constructor
CIn the Dispose method
DIn the Main method
✗ Incorrect
Dispose is used to clean up resources, including unsubscribing from events.
What does an event publisher hold that can cause memory leaks?
ACopies of subscriber objects
BReferences to subscribers
CGarbage collector
DEvent logs
✗ Incorrect
The publisher holds references to subscribers via event handlers.
Which pattern helps avoid strong references in event subscriptions?
AWeak event pattern
BSingleton pattern
CFactory pattern
DObserver pattern
✗ Incorrect
Weak event pattern uses weak references to allow garbage collection.
Explain why unsubscribing from events is important for memory management in C#.
Think about how references affect object lifetime.
You got /4 concepts.
Describe a good practice to ensure event handlers are unsubscribed properly.
Consider how to clean up resources in classes.
You got /4 concepts.
Practice
(1/5)
1. What happens if you do not unsubscribe from an event in C#?
easy
A. The event will automatically unsubscribe after the first call.
B. The program will throw a compile-time error.
C. The subscriber object may not be garbage collected, causing a memory leak.
D. The event handler will be called only once.
Solution
Step 1: Understand event subscription behavior
When an object subscribes to an event, the event publisher holds a reference to the subscriber's method.
Step 2: Effect of not unsubscribing
If you don't unsubscribe, the subscriber object remains referenced and cannot be garbage collected, causing a memory leak.
Final Answer:
The subscriber object may not be garbage collected, causing a memory leak. -> Option C
Quick Check:
Not unsubscribing = memory leak [OK]
Hint: Always unsubscribe to avoid memory leaks and keep memory clean [OK]
Common Mistakes:
Assuming events auto-unsubscribe
Thinking unsubscribing causes errors
Believing event handlers run only once
2. Which syntax correctly unsubscribes a method named OnDataReceived from an event DataReceived?
easy
A. DataReceived -= OnDataReceived;
B. DataReceived += OnDataReceived;
C. DataReceived = null;
D. DataReceived.Unsubscribe(OnDataReceived);
Solution
Step 1: Recall event unsubscription syntax
In C#, to unsubscribe from an event, use the '-=' operator with the same method.
Step 2: Match correct syntax
DataReceived -= OnDataReceived; uses 'DataReceived -= OnDataReceived;', which is the correct way to unsubscribe.
Final Answer:
DataReceived -= OnDataReceived; -> Option A
Quick Check:
Unsubscribe syntax = '-=' operator [OK]
Hint: Use '-=' with the same method to unsubscribe events [OK]
Common Mistakes:
Using '+=' instead of '-=' to unsubscribe
Trying to assign null to the event
Using non-existent Unsubscribe method
3. What will be the output of the following code?
using System;
class Program {
static event Action MyEvent;
static void Handler() => Console.WriteLine("Called");
static void Main() {
MyEvent += Handler;
MyEvent -= Handler;
MyEvent?.Invoke();
}
}
medium
A. Called
B. No output
C. NullReferenceException
D. Compile-time error
Solution
Step 1: Analyze event subscription and unsubscription
The method Handler is subscribed then immediately unsubscribed from MyEvent.
Step 2: Check event invocation
Since no handlers remain, MyEvent is null, so MyEvent?.Invoke() does nothing and prints no output.
Final Answer:
No output -> Option B
Quick Check:
Unsubscribed event = no call [OK]
Hint: Unsubscribed event handlers do not run when invoked [OK]
Common Mistakes:
Expecting output despite unsubscription
Ignoring null conditional operator
Thinking event throws exception if empty
4. Identify the problem in this code snippet related to event unsubscription:
class Publisher {
public event Action OnChange;
public void Raise() => OnChange?.Invoke();
}
class Subscriber {
public void Subscribe(Publisher p) {
p.OnChange += HandleChange;
}
void HandleChange() {
Console.WriteLine("Changed");
}
}
medium
A. Subscriber never unsubscribes, causing potential memory leaks.
B. Event is invoked incorrectly with null conditional operator.
C. Handler method signature does not match event delegate.
D. Publisher event is not declared as static.
Solution
Step 1: Review subscription and unsubscription
The Subscriber subscribes to the event but never unsubscribes.
Step 2: Understand consequences
Without unsubscription, the Subscriber object remains referenced by Publisher, causing memory leaks.
Final Answer:
Subscriber never unsubscribes, causing potential memory leaks. -> Option A
Quick Check:
Missing unsubscribe = memory leak risk [OK]
Hint: Always unsubscribe to avoid memory leaks in event handlers [OK]
Common Mistakes:
Ignoring unsubscription importance
Confusing static and instance events
Assuming null conditional operator causes errors
5. You have a long-running application where multiple subscribers attach to a static event but never unsubscribe. What is the best approach to prevent memory leaks?
hard
A. Replace events with polling loops to avoid subscription issues.
B. Make the event instance-level instead of static to avoid leaks.
C. Ignore unsubscription because garbage collector handles it automatically.
D. Use weak event patterns or explicitly unsubscribe when subscribers are no longer needed.
Solution
Step 1: Understand static event references
Static events hold references for the app lifetime, so subscribers never get garbage collected unless unsubscribed.
Step 2: Best practice to avoid leaks
Using weak event patterns or explicitly unsubscribing prevents memory leaks by releasing subscriber references.
Final Answer:
Use weak event patterns or explicitly unsubscribe when subscribers are no longer needed. -> Option D
Quick Check:
Weak events or unsubscribe = prevent leaks [OK]
Hint: Use weak events or unsubscribe explicitly to avoid leaks [OK]
Common Mistakes:
Assuming GC cleans static event subscribers
Changing event to instance-level without reason
Replacing events with inefficient polling
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.