C# Events
In this chapter you will learn:
Description
Events are a language feature that formalizes the pattern of broadcaster and subscriber.
An event is a construct that exposes just the subset of delegate features required for the broadcaster/ subscriber model.
Syntax
The easiest way to declare an event is to put the event
keyword in front of a delegate
member:
public class Broadcaster
{
public event ProgressReporter Progress;
}
Code within the Broadcaster type has full access to Progress and can treat it as a delegate. Code outside of Broadcaster can only perform += and -= operations on the Progress event.
Example
The Rectangle
class fires its ValueChanged
event every
time the Value of the Rectangle changes:
public delegate void ValueChangeHandler (decimal oldValue,
decimal newValue);
// w w w. j ava 2 s . co m
public class Rectangle
{
string symbol;
decimal myValue;
public Rectangle (string symbol) { this.symbol = symbol; }
public event ValueChangeHandler ValueChanged;
public decimal Value
{
get { return myValue; }
set
{
if (myValue == value) return; // Exit if nothing has changed
if (ValueChanged != null) // If invocation list not empty,
ValueChanged (myValue, value); // fire event.
myValue = value;
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What is C# Standard Event Pattern
- Step 1: subclass EventArgs
- Step 2: define a delegate for the event
- Step 3:Fire event
- Example for standard event pattern