Events & Delegates

  • Thread starter Thread starter Guest
  • Start date Start date
Well, kind of. Events are methods of a class that are associated with some
delegate type, but are marked with the "event" keyword so that the compiler
knows what to do with them. "event" in C# is really nothing more than an
access modifier like "private", "public", or "sealed". The specific level
of access granted by the "event" keyword depends on whether code that's
referencing that method is part of the class that defined the method, or
outside of the class. Code that is part of the class is allowed to call the
method (and thereby, "raise" the event), whereas code outside of the class
is only allowed to subscribe to the event by using the += operator to add an
appropriate delegate method to the event method's list of subscribers. For
instance, if class A has an event called "Fire", then class A is allowed to
do this:

// Declare a type signature for the Fire event:
public delegate void AFireType(object sender, EventArgs e);
// create an instance of the AFireType delegate and mark it as an event:
public event AFireType Fire;

// elsewhere...
if(temperature >= (Farenheit)415.0) {
if(Fire != null)
Fire()
}

Class B, however, can't do anything more than this:

// define a handler for class A's Fire event:
public void OnFire(object sender, EventArgs e) { // what to do if something
is on fire };

// Create an A object and subscribe to it's Fire event:
A MyA = new A();
MyA.Fire += new A.AFireType(OnFire)
 
Back
Top