Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Event unsubscription and memory in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Event Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this event subscription code?

Consider the following C# code where an event is subscribed and then triggered. What will be printed to the console?

C Sharp (C#)
using System;

class Publisher {
    public event Action OnChange;
    public void Raise() {
        OnChange?.Invoke();
    }
}

class Subscriber {
    public void Subscribe(Publisher p) {
        p.OnChange += () => Console.WriteLine("Event triggered");
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber();
        sub.Subscribe(pub);
        pub.Raise();
    }
}
ARuntime exception
BEvent triggered
CNo output
DCompilation error
Attempts:
2 left
💡 Hint

Think about what happens when the event is raised after subscription.

❓ Predict Output
intermediate
2:00remaining
What happens if you forget to unsubscribe from an event?

Given the code below, what will be the output after GC.Collect() is called?

C Sharp (C#)
using System;

class Publisher {
    public event Action OnChange;
    public void Raise() {
        OnChange?.Invoke();
    }
}

class Subscriber {
    public Subscriber(Publisher p) {
        p.OnChange += Handler;
    }
    void Handler() {
        Console.WriteLine("Handled event");
    }
    ~Subscriber() {
        Console.WriteLine("Subscriber finalized");
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber(pub);
        sub = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        pub.Raise();
    }
}
ANo output
B
Subscriber finalized
Handled event
C
Handled event
Subscriber finalized
DHandled event
Attempts:
2 left
💡 Hint

Think about whether the subscriber object is collected by the garbage collector.

🔧 Debug
advanced
3:00remaining
Why does this event unsubscription fail to prevent memory leaks?

Examine the code below. The developer tries to unsubscribe the event to avoid memory leaks but it doesn't work. Why?

C Sharp (C#)
using System;

class Publisher {
    public event Action OnChange;
    public void Raise() => OnChange?.Invoke();
}

class Subscriber {
    private Publisher _pub;
    public Subscriber(Publisher pub) {
        _pub = pub;
        _pub.OnChange += Handler;
    }
    public void Unsubscribe() {
        _pub.OnChange -= () => Console.WriteLine("Handled");
    }
    private void Handler() {
        Console.WriteLine("Handled");
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber(pub);
        sub.Unsubscribe();
        pub.Raise();
    }
}
AThe lambda used in Unsubscribe is a different delegate instance than the one subscribed, so unsubscription fails.
BThe event is null so unsubscription throws an exception.
CThe Handler method is private and cannot be unsubscribed.
DThe Publisher class does not support unsubscription.
Attempts:
2 left
💡 Hint

Consider how delegates and lambdas work in C# when subscribing and unsubscribing.

❓ Predict Output
advanced
3:00remaining
What is the output when using weak event pattern?

Consider this code using a weak event pattern to avoid memory leaks. What will be printed?

C Sharp (C#)
using System;
using System.Runtime.CompilerServices;

class Publisher {
    public event Action OnChange;
    public void Raise() => OnChange?.Invoke();
}

class Subscriber {
    public Subscriber(Publisher pub) {
        WeakReference<Subscriber> weakRef = new WeakReference<Subscriber>(this);
        pub.OnChange += () => {
            if (weakRef.TryGetTarget(out var target)) {
                target.Handler();
            }
        };
    }
    public void Handler() {
        Console.WriteLine("Handled via weak ref");
    }
    ~Subscriber() {
        Console.WriteLine("Subscriber finalized");
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber(pub);
        sub = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        pub.Raise();
    }
}
AHandled via weak ref
B
Subscriber finalized
Handled via weak ref
C
Subscriber finalized
No output from event
DNo output
Attempts:
2 left
💡 Hint

Think about whether the subscriber is still alive when the event is raised.

🧠 Conceptual
expert
3:00remaining
Which statement best explains event unsubscription's role in memory management?

Choose the best explanation for why unsubscribing from events is important to prevent memory leaks in C#.

AEvent subscriptions create strong references from the publisher to the subscriber, preventing garbage collection unless unsubscribed.
BUnsubscribing events automatically frees all memory used by the subscriber immediately.
CEvents use weak references by default, so unsubscription is only needed for performance reasons.
DSubscribers hold references to publishers, so unsubscribing breaks this link to avoid leaks.
Attempts:
2 left
💡 Hint

Consider how event delegates hold references internally.

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

  1. Step 1: Understand event subscription behavior

    When an object subscribes to an event, the event publisher holds a reference to the subscriber's method.
  2. 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.
  3. Final Answer:

    The subscriber object may not be garbage collected, causing a memory leak. -> Option C
  4. 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

  1. Step 1: Recall event unsubscription syntax

    In C#, to unsubscribe from an event, use the '-=' operator with the same method.
  2. Step 2: Match correct syntax

    DataReceived -= OnDataReceived; uses 'DataReceived -= OnDataReceived;', which is the correct way to unsubscribe.
  3. Final Answer:

    DataReceived -= OnDataReceived; -> Option A
  4. 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

  1. Step 1: Analyze event subscription and unsubscription

    The method Handler is subscribed then immediately unsubscribed from MyEvent.
  2. Step 2: Check event invocation

    Since no handlers remain, MyEvent is null, so MyEvent?.Invoke() does nothing and prints no output.
  3. Final Answer:

    No output -> Option B
  4. 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

  1. Step 1: Review subscription and unsubscription

    The Subscriber subscribes to the event but never unsubscribes.
  2. Step 2: Understand consequences

    Without unsubscription, the Subscriber object remains referenced by Publisher, causing memory leaks.
  3. Final Answer:

    Subscriber never unsubscribes, causing potential memory leaks. -> Option A
  4. 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

  1. Step 1: Understand static event references

    Static events hold references for the app lifetime, so subscribers never get garbage collected unless unsubscribed.
  2. Step 2: Best practice to avoid leaks

    Using weak event patterns or explicitly unsubscribing prevents memory leaks by releasing subscriber references.
  3. Final Answer:

    Use weak event patterns or explicitly unsubscribe when subscribers are no longer needed. -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard