How can I unsubscribe to this .NET event?

.net, asp.net, c#, event-handling, events

Solution

It's not possible to unsubscribe that anonymous delegate. You would need to store it in a variable and unsubscribe it later:

EndRequestEventHandler handler = (sender, e) =>
{
    if (some logic) 
        HandleCustomErrors(httpApplication, sender, e,
                          (HttpStatusCode)httpApplication.Response.StatusCode);
};

httpApplication.EndRequest += handler;
// do stuff
httpApplication.EndRequest -= handler;

Problem

I wish to programatically unsubscribe to an event, which as been wired up. I wish to know how I can unsubscribe to the `EndRequest` event. I'm not to sure how to do this, considering i'm using inline code. (is that the correct technical term?) I know i can use the `some.Event -= MethodName` to unsubscribe .. but I don't have a method name, here. The reason I'm using the inline code is because I wish to reference a variable defined outside of the event (which I required .. but feels smelly... i feel like I need to pass it in). Any suggestions? Code time.. ``` public void Init(HttpApplication httpApplication) { httpApplication.EndRequest += (sender, e) => { if (some logic) HandleCustomErrors(httpApplication, sender, e, (HttpStatusCode)httpApplication.Response.StatusCode); }; httpApplication.Error += (sender, e) => HandleCustomErrors(httpApplication, sender, e); } private static void HandleCustomErrors(HttpApplication httpApplication, object sender, EventArgs e, HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError) { ... } ``` This is just some sample code I have, for me to handle errors in a `ASP.NET` application. NOTE: Please don't turn this into a discussion about ASP.NET error handling. I'm just playing around with events and using these events for some sample R&D / learning.

Original source