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

Event unsubscription and memory in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Event unsubscription and memory
📖 Scenario: Imagine you have a simple program where a Button can be clicked, and a Listener responds to the click event. If you don't unsubscribe the listener when it's no longer needed, it can cause memory problems.
🎯 Goal: You will create a Button class with a click event, a Listener class that subscribes to the event, then unsubscribe the listener to avoid memory leaks.
📋 What You'll Learn
Create a Button class with a Click event
Create a Listener class with a method to handle the click
Subscribe the listener to the button's click event
Unsubscribe the listener from the click event
Print messages to show when the event is handled and when unsubscribed
💡 Why This Matters
🌍 Real World
Events are used in user interfaces, games, and many applications to respond to user actions or system changes.
💼 Career
Understanding event subscription and unsubscription is important for writing efficient, memory-safe C# applications.
Progress0 / 4 steps
1
Create the Button class with a Click event
Create a class called Button with a public event Click of type EventHandler. Also add a method OnClick() that invokes the Click event if it is not null.
C Sharp (C#)
Need a hint?

Use public event EventHandler? Click; and invoke it with Click?.Invoke(this, EventArgs.Empty);

2
Create the Listener class and subscribe to the Click event
Create a class called Listener with a method HandleClick that matches the EventHandler signature and prints "Button clicked!". Then create a Button instance called button and a Listener instance called listener. Subscribe listener.HandleClick to button.Click.
C Sharp (C#)
Need a hint?

Make sure HandleClick matches EventHandler signature and subscribe with button.Click += listener.HandleClick;

3
Unsubscribe the listener from the Click event
Add a line to unsubscribe listener.HandleClick from button.Click using -=. This should be after the subscription line.
C Sharp (C#)
Need a hint?

Use button.Click -= listener.HandleClick; to unsubscribe.

4
Test the event subscription and unsubscription
Call button.OnClick() twice: once before unsubscribing and once after unsubscribing. Print "Clicked once" before the first call and "Clicked twice" before the second call to show the difference.
C Sharp (C#)
Need a hint?

Print messages before each OnClick() call to show when the event handler runs.