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

Event unsubscription and memory in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Unsubscribing from events helps stop unwanted actions and frees memory. It keeps your program clean and fast.

When you no longer want to receive updates from an event.
To prevent memory leaks in long-running applications.
When an object that subscribed to an event is about to be destroyed.
To avoid unexpected behavior from events firing after an object is gone.
Syntax
C Sharp (C#)
eventSource.EventName -= EventHandlerMethod;

Use the same method you used to subscribe, but with '-=' to unsubscribe.

Unsubscribing is important especially in applications with many events or long lifetimes.

Examples
This line removes the method OnSomeEvent from the SomeEvent event.
C Sharp (C#)
publisher.SomeEvent -= OnSomeEvent;
Stops the Button_Click method from running when the button is clicked.
C Sharp (C#)
button.Click -= Button_Click;
Sample Program

This program shows a publisher sending an event and a subscriber listening. After unsubscribing, the subscriber no longer reacts, which helps avoid memory leaks and unwanted calls.

C Sharp (C#)
using System;

class Publisher
{
    public event EventHandler? RaiseEvent;

    public void DoSomething()
    {
        Console.WriteLine("Doing something...");
        RaiseEvent?.Invoke(this, EventArgs.Empty);
    }
}

class Subscriber
{
    public void Subscribe(Publisher pub)
    {
        pub.RaiseEvent += HandleEvent;
    }

    public void Unsubscribe(Publisher pub)
    {
        pub.RaiseEvent -= HandleEvent;
    }

    private void HandleEvent(object? sender, EventArgs e)
    {
        Console.WriteLine("Event received in subscriber.");
    }
}

class Program
{
    static void Main()
    {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber();

        sub.Subscribe(pub);
        pub.DoSomething();  // Event fires, subscriber reacts

        sub.Unsubscribe(pub);
        pub.DoSomething();  // Event fires, but subscriber does not react
    }
}
OutputSuccess
Important Notes

Always unsubscribe from events when the subscriber is no longer needed.

Failing to unsubscribe can cause memory leaks because the publisher keeps a reference to the subscriber.

Use weak event patterns or tools if manual unsubscription is difficult.

Summary

Unsubscribing stops event notifications and frees memory.

Use '-=' with the same method to unsubscribe from an event.

Always unsubscribe to avoid memory leaks and unexpected behavior.