C# Events

In this chapter you will learn:

  1. What are C# Events
  2. How to define an event
  3. Example for an event

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:

  1. What is C# Standard Event Pattern
  2. Step 1: subclass EventArgs
  3. Step 2: define a delegate for the event
  4. Step 3:Fire event
  5. Example for standard event pattern
Home »
  C# Tutorial »
    C# Types »
      C# Event
C# Events
C# Standard Event Pattern