This is a simple implementation of a class that provides an event.
public class ChangeNotifier {
This class can be used as follows:
public void SomeMethod() { ChangeNotifier notifier = new ChangeNotifier(10); // Subscribe to the event and output the number when it fires. notifier.NumberChanged += (s, e) => Console.Writeline(notifier.Number.ToString()); notifier.Number = 10; // Does nothing, this is the same value notifier.Number = 20; // Outputs "20" because the event is raised and the lambda runs. }
As for the control flow, execution of the flow in SomeMethod() . We create a new ChangeNotifier and call its constructor. This assigns a value of 10 to the private element num .
Then we subscribe to the event using the syntax += . This operator accepts a delegate on the right side (in our case, this delegate is a lambda) and adds it to the collection of delegates at the event. This operation does not execute the code that we wrote in ChangeNotifier . It can be configured using the add and remove methods on the event, if you want, but rarely need to do this.
Then we perform a couple of simple operations on the Number property. First we assign 10 , which runs the set method on the Number property with value = 10 . But the num member is already evaluated at 10 , so the initial conditional value is set to false and nothing happens.
Then we do the same with 20 . The value is different this time, so we assign a new value to num and fire the event. First, we verify that the event is not zero. It is zero if nothing has subscribed to it. If it is not null (that is, if something is subscribed to it), we start it using the standard method / delegate syntax. we just call the event with the event arguments. This will call all methods that subscribe to the event, including our lambda, which will execute Console.WriteLine() .
Henrik successfully fulfilled the potential race condition, which exists if one thread can be in the Number setter and the other listener unsubscribes. I do not consider this a common thing for those who do not yet understand how events work, but if you are concerned about this possibility, change these lines:
if (this.NumberChanged != null) this.NumberChanged(this, EventArgs.Empty);
will look something like this:
var tmp = this.NumberChanged; if (tmp != null) tmp(this, EventArgs.Empty);