Get to know Events - CSharp Custom Type

CSharp examples for Custom Type:Event

Introduction

Events are a language feature that formalizes broadcaster and subscribers.

The broadcaster contains a delegate field and decides when to broadcast by invoking the delegate.

A subscriber decides when to start and stop listening by calling += and -= on the broadcaster's delegate.

A subscriber does not know about, or interfere with, other subscribers.

The main purpose of events is to prevent subscribers from interfering with one another.

The easiest way to declare an event is to put the event keyword in front of a delegate member:

Code within the Broadcaster type has full access to PriceChanged and can treat it as a delegate.

Code outside of Broadcaster can only perform += and -= operations on the PriceChanged event.


// Delegate definition
public delegate void PriceChangedHandler (decimal oldPrice, decimal newPrice);

public class Broadcaster
{
  // Event declaration
  public event PriceChangedHandler PriceChanged;
}

Related Tutorials