C# Events

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);
/*from  w  w  w  .  ja v a2s.  c  o  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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor