Unsubscribe anonymous method in C#

Is it possible to unsubscribe an anonymous method from an event? If I subscribe to an event like this: void MyMethod() { Console.WriteLine(“I did it!”); } MyEvent += MyMethod; I can un-subscribe like this: MyEvent -= MyMethod; But if I subscribe using an anonymous method: MyEvent += delegate(){Console.WriteLine(“I did it!”);}; is it possible to unsubscribe … Read more

Is there a reason for C#’s reuse of the variable in a foreach?

When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: foreach (var s in strings) { query = query.Where(i => i.Prop == s); // access to modified closure … } Due to the modified closure, the above code will cause all of … Read more