Note that there are some explanatory texts on larger screens.

plurals
  1. POEventHandlers and Anonymous Delegates / Lambda Expressions
    primarykey
    data
    text
    <p>I'm hoping to clear some things up with anonymous delegates and lambda expressions being used to create a method for event handlers in C#, for myself at least.</p> <p>Suppose we have an event that adds either an anonymous delegate or a lambda expression (for you lucky crowds that can use newer versions of .NET). </p> <pre><code>SomeClass.SomeEvent += delegate(object o, EventArg e) { /* do something */ }; </code></pre> <p>I have read that people in the past have forgotten about events that still have handlers which prevent the class from being garbage collected. How would one go about removing the added handler without just setting SomeEvent to null within the class. Wouldn't the following be an entirely new handler?</p> <pre><code>SomeClass.SomeEvent -= delegate(object o, EventArg e) { /* do something */ }; </code></pre> <p>I could see storing the anonymous delegate or lambda expression in a variable. But that, to me at least, seems to defeat the entire purpose of being able to simply and succinctly add an event handler.</p> <pre><code>SomeEventDelegate handler = new SomeEventDelegate(delegate(object o, EventArg e) { /* do something */ }); SomeClass.SomeEvent += handler; // ... stuff SomeClass.SomeEvent -= handler; </code></pre> <p>Again, I understand that you could just do...</p> <pre><code>public override Dispose(bool disposing) { _someEvent = null; this.Dispose(); } </code></pre> <p>But I'm more interesting with just removing the dynamically created method from the event. Hopefully someone can shed some light onto this for me. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload