public void ActionAddRemoveMethod() { var x = new PublicAction(); x.MyEvent += ActionToRemove2; x.MyEvent -= ActionToRemove2; x.OnMyEvent(); }
public void ActionAddRemoveAnonymousFunction() { var x = new PublicAction(); x.MyEvent += (PublicAction a) => { ActionToRemove2(a); }; x.MyEvent -= (PublicAction a) => { ActionToRemove2(a); }; x.OnMyEvent(); }
public void ActionAddRemoveLambda() { var x = new PublicAction(); x.MyEvent += (a) => ActionToRemove2(a); x.MyEvent -= (a) => ActionToRemove2(a); x.OnMyEvent(); }
public void ActionAddRemoveMethodRef() { var x = new PublicAction(); Action <PublicAction> actionToRemove = ActionToRemove2; x.MyEvent += actionToRemove; x.MyEvent -= actionToRemove; x.OnMyEvent(); }
public void ActionAddRemoveLocalFunction() { var x = new PublicAction(); void actionToRemove(PublicAction a) { ActionToRemove2(a); } x.MyEvent += actionToRemove; x.MyEvent -= actionToRemove; x.OnMyEvent(); }
public void ObjectInitializers() { bool firstHappened = false; bool secondHappened = false; var x = new PublicAction() { // So if we use a publicly accessible Action (without the event keyword), // we can do this, which is cool MyEvent = (a) => { firstHappened = true; } }; // And still do multiple handlers, like this: x.MyEvent += (a) => { secondHappened = true; }; x.OnMyEvent(); Assert.True(firstHappened); Assert.True(secondHappened); }
public void BadEncapsulation() { bool firstHappened = false; bool secondHappened = false; var x = new PublicAction() { MyEvent = (a) => { firstHappened = true; } }; // And the syntax folks are familiar with still works x.MyEvent += (a) => { secondHappened = true; }; // But if we use a publicly accessible Action (without the event keyword), that means // that anyone could nuke our event handlers, like this: x.MyEvent = null; x.OnMyEvent(); Assert.False(firstHappened); Assert.False(secondHappened); }