Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnHooking Events with Lambdas in C#

Tags:

c#

lambda

events

I often run into a situation where I want to subscribe to an event, but I want to use a lambda to do so:

public class Observable
{
    public event EventHandler SomethingHappened;

    public void DoSomething()
    {
        // Do Something...
        OnSomethingHappened();
    }
}

// Somewhere else, I hook the event
observable.SomethingHappened += (sender, args) => Console.WriteLine("Something Happened");

The problem I run into is that I don't know how to unhook the event. Since the lambda creates an anonymous delegate under the hood, I have nothing to call -= on.

Now, I could just create a method:

private void SomethingHappened(object sender, EventArgs args)
{
    Console.WriteLine("Something Happened");
}

And then I can hook/unhook all I want:

observable.SomethingHappened += SomethingHappened;
observable.SomethingHappened -= SomethingHappened;

But I'd really, really, really like to use my lambda instead. In a more complicated example, lambdas come in really handy here.

I am pretty sure that I am out of luck... but I was wondering if anyone out there has figured out a way to do this?

like image 761
Brian Genisio Avatar asked May 13 '09 19:05

Brian Genisio


2 Answers

This question was already asked

  • How to unsubscribe from an event which uses a lambda expression?
  • Unsubscribe anonymous method in C#

The answer is: put your lambda in a variable.

EventHandler handler = (sender, args) => Console.WriteLine("Something Happened");
observable.SomethingHappened +=  handler;
observable.SomethingHappened -=  handler;
like image 179
Stefan Steinegger Avatar answered Sep 28 '22 13:09

Stefan Steinegger


Unforutantely there is not a great way to do this. You are really stuck with one of two options

  • Use a method as you described
  • Assign the lambda to a variable and use the variable to add / remove the event
like image 22
JaredPar Avatar answered Sep 28 '22 12:09

JaredPar