#388 – Declaring and Using Private Events
August 12, 2011 Leave a comment
You can declare private events in a class and they can be either instance or static events. A private event is one that code within the class can subscribe to, but that is not visible to code outside the class.
For example, we can create a private static event in the Dog class that will fire whenever a new dog is created.
private static event EventHandler<DogCreatedEventArgs> DogCreated;
This event will be visible only to code within the Dog class.
In the static constructor, we attach a handler that will record each Dog created.
static Dog() { Dog.DogCreated += new EventHandler<DogCreatedEventArgs>(Dog_DogCreated); } static List<string> DogList = new List<string>(); static void Dog_DogCreated(object sender, DogCreatedEventArgs e) { DogList.Add(e.Name); }
Finally, we fire the event from the instance constructor.
public Dog(string name) { Name = name; if (Dog.DogCreated != null) Dog.DogCreated(this, new DogCreatedEventArgs(name)); }