Recall & Review
beginner
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#?
✗ Incorrect
The '-=' operator removes the event handler from the event's invocation list.
What problem can occur if you never unsubscribe from events?
✗ Incorrect
Not unsubscribing keeps references alive, causing memory leaks.
Where is a good place to unsubscribe from events in a subscriber class?
✗ Incorrect
Dispose is used to clean up resources, including unsubscribing from events.
What does an event publisher hold that can cause memory leaks?
✗ Incorrect
The publisher holds references to subscribers via event handlers.
Which pattern helps avoid strong references in event subscriptions?
✗ 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.