C# events tutorial and simple explanation

C# events

Events are very helpful in managing interactions between calling object and called object. In this example we capture the essence of c# events. Here’s how the discussion between two objects goes:

  • Object COUNTER has an internal counter that can be incremented by AddOne() method
  • Program initializes Object 1 and sets the threshold to 5
  • Program calls Object 1’s AddOne() method 10 times. From 6th to 10th time the threshold will be surpassed
  • Program wants to be notified whenever Object COUNTER’s total surpasses the threshold
  • Object COUNTER exposes a public event
  • Program wires up that event to one of its method so that it can listen when COUNTER fires the event
  • Object COUNTER checks when the threshold is surpassed. If surpassed, it sends the event’s listener information
  • Program catches this message and displays appropriate message

Let’s look at the example based on http://msdn.microsoft.com/en-us/library/9aackb16(v=vs.110).aspx. It was modified by adding comments and relevant variable names to build an easy-to-use example for myself.

Check out MSDN’s article on events for more information.