public void BetterEncapsulation() { bool firstHappened = false; bool secondHappened = false; bool thirdHappened = false; var x = new LessPublicAction() { MyEvent = (a) => { firstHappened = true; } }; // And the expected syntax still works x.MyEvent += (a) => { secondHappened = true; }; // We can ignore null (in this case, just add it as a null action to the subscriber list) // And only let the actual backing property be modified internally during Dispose // So we avoid having others nuke our events, which is great x.MyEvent = null; // Though this is probably going to be confusing; it looks like it should // replace the existing Action, but instead it simply adds this one to the list x.MyEvent = (a) => { thirdHappened = true; }; x.OnMyEvent(); Assert.True(firstHappened); Assert.True(secondHappened); Assert.True(thirdHappened); }
public void BetterEncapsulationFailsRemoval() { bool firstHappened = false; var x = new LessPublicAction() { MyEvent = (a) => { firstHappened = true; } }; x.MyEvent += ActionToRemove; // This will fail - ActionToRemove will still be called // Because our hack to disallow Event = null nuking prevents proper // updating of the modified invocation list x.MyEvent -= ActionToRemove; x.OnMyEvent(); Assert.True(firstHappened); }