How do you access the number of times a delegate has been called?

I am currently writing a test for a piece of functionality. I need to count how many times an event handler has been called. In this example I want to ensure the delegate 'failureHandler' is never called.

I have achieved what I want from a test perspective by doing an Assert.Fail() if it is called. What I want do though is count the number of times a delegate is called for use in other parts of the test.

I believe I read somewhere you could access this information via property but I can't remember where I read it!

Action failureHandler = 
                completed => Assert.Fail("Not all tasks have been completed");

_testObj.TaskCompletedForItems += failureHandler;
Jon Skeet
people
quotationmark

No, there's no standard property for that... but you can easily use the fact that a lambda expression is a closure to emulate it:

int callCount = 0;
Action handler = () => callCount++;

_testObj.TaskCompletedForItems += handler;
// Do stuff

Assert.AreEqual(expectedCount, callCount);

people

See more on this question at Stackoverflow