I tried to unsubscribe from a lambda within itself. I used the MethodInfo class for getting information about a lambda and the Delegate.CreateDelegate method for creating the same method as a lambda. So it works fine if a lambda created in one of the class methods that contains the event i use but doesn’t work in another class method (binding exception).
Here’s the code:
public class TestClass
{
public event Action SomeEvent;
public void OnSomeEvent()
{
if (SomeEvent != null)
{
SomeEvent();
}
}
public TestClass()
{
//IT WORKS FINE!!!
//SomeEvent += () =>
//{
// Console.WriteLine("OneShotLambda");
// MethodInfo methodInfo = MethodInfo.GetCurrentMethod() as MethodInfo;
// Action action = (Action)Delegate.CreateDelegate(typeof(Action), this, methodInfo);
// SomeEvent -= action;
//};
}
}
class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass();
t.SomeEvent += () =>
{
Console.WriteLine("OneShotLambda");
MethodInfo methodInfo = MethodInfo.GetCurrentMethod() as MethodInfo;
//GOT AN ERROR
Action action = (Action)Delegate.CreateDelegate(typeof(Action), t, methodInfo);
t.SomeEvent -= action;
};
t.OnSomeEvent();
t.OnSomeEvent(); //MUST BE NO MESSAGE
}
}
The reason why it doesn’t work is that you pass in
tas the second parameter toCreateDelegatewhen you should passnull. This is due to the fact that the method created for the lambda will be a static method. Otherwise it couldn’t be used from the staticMainmethod. And the documentation clearly states that you need to passnullfor static methods.Having said that, you would be better off doing it differently:
This code is more readable and understandable and additionally performs better.