0
0
C Sharp (C#)programming~5 mins

Event unsubscription and memory in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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#?
A!=
B+=
C==
D-=
What problem can occur if you never unsubscribe from events?
AMemory leaks
BFaster execution
CAutomatic unsubscription
DNo effect
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
What does an event publisher hold that can cause memory leaks?
ACopies of subscriber objects
BReferences to subscribers
CGarbage collector
DEvent logs
Which pattern helps avoid strong references in event subscriptions?
AWeak event pattern
BSingleton pattern
CFactory pattern
DObserver pattern
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.