C#
  Home arrow C# arrow Page 3 - Delegates and Events in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Delegates and Events in C#
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-09-25

    Table of Contents:
  • Delegates and Events in C#
  • Events
  • Standard Event Pattern
  • Event Accessors

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Delegates and Events in C# - Standard Event Pattern


    (Page 3 of 4 )

    The .NET Framework defines a standard pattern for writing events. Its purpose is to provide consistency across both Framework and user code. At the core of the standard event pattern is System.EventArgs: a predefined Framework class with no members (other than the static Empty property).EventArgsis a base class for conveying information for an event. In ourStockexample, we would subclassEventArgsto convey the old and new prices when aPriceChangedevent is fired:

      public class PriceChangedEventArgs : System.EventArgs
     
    {
       
    public readonly decimal LastPrice;
       
    public readonly decimal NewPrice;

        public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
       
    {
         
    LastPrice = lastPrice;
         
    NewPrice = newPrice;
       
    }
      }

    For reusability, theEventArgssubclass is named according to the information it contains (rather than the event for which it will be used). It typically exposes data as properties or as read-only fields.

    With anEventArgssubclass in place, the next step is to choose or define a delegate for the event. There are three rules:

    • It must have avoidreturn type.
    • It must accept two arguments: the first of typeobject, and the second a subclass ofEventArgs. The first argument indicates the event broadcaster, and the second argument contains the extra information to convey.
    • Its name must end in “EventHandler”.

    The Framework defines a generic delegate calledSystem.EventHandler<>that satisfies these rules:

      public delegate void EventHandler<TEventArgs>
        (object source, TEventArgs e) where TEventArgs : EventArgs;

    Before generics existed in the language (prior to C# 2.0), we would have had to instead write a custom delegate as follows:

      public delegate void PriceChangedHandler (object sender,
        PriceChangedEventArgs e);

    For historical reasons, most events within the Framework use delegates defined in this way.

    The next step is to define an event of the chosen delegate type. Here, we use the genericEventHandler delegate:

      public class Stock
      {
       
    ...

        public event EventHandler<PriceChangedEventArgs>PriceChanged;
     
    } 

    Finally, the pattern requires that you write a protected virtual method that fires the event. The name must match the name of the event, prefixed with the word “On”, and then accept a singleEventArgsargument:

      public class Stock
      {
        ...

        public event EventHandler<PriceChangedEventArgs> PriceChanged;

        protected virtual void OnPriceChanged (PriceChangedEventArgs e)
        {
          if (PriceChanged != null) PriceChanged (this, e);
        }
      }

    This provides a central point from which subclasses can invoke or override the event.

    Here’s the complete example:

      using System;

      public class PriceChangedEventArgs : EventArgs
      {
       
    public readonly decimal LastPrice;
       
    public readonly decimal NewPrice;

        public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
        {
         
    LastPrice = lastPrice; NewPrice = newPrice;
        }
      }

      public class Stock
      {
        string symbol;
        decimal price;

        public Stock (string symbol) {this.symbol = symbol;}

        public event EventHandler<PriceChangedEventArgs> PriceChanged;

        protected virtual void OnPriceChanged (PriceChangedEventArgs e)
        {
          if (PriceChanged != null) PriceChanged (this, e);
        }

        public decimal Price
       
    {
          get { return price; }
          set
          {
            if (price == value) return;
            OnPriceChanged (new PriceChangedEventArgs (price, value));
            price = value;
         
    }
        }
      }

      class Test
      {
        static void Main()
        {
         
    Stock stock = new Stock ("THPW");
          stock.Price = 27.10M;
          // register with the PriceChanged event
          stock.PriceChanged += stock_PriceChanged;
          stock.Price = 31.59M;
       
    }

        static void stock_PriceChanged (object sender, PriceChangedEventArgs e)
        {
          if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
            Console.WriteLine ("Alert, 10% stock price increase!");
        }
      }

    The predefined nongenericEventHandler delegate can be used when an event doesn’t carry extra information. In this example, we rewriteStocksuch that thePriceChangedevent is fired after the price changes, and no information about the event is necessary, other than it happened. We also make use of theEventArgs.Emptyproperty, in order to avoid unnecessarily instantiating an instance ofEventArgs.

      public class Stock
      {
        string symbol;
        decimal price;

        public Stock (string symbol) {this.symbol = symbol;}

        public event EventHandler PriceChanged;

        protected virtual void OnPriceChanged (EventArgs e)
        {
          if (PriceChanged != null) PriceChanged (this, e);
        }

        public decimal Price
       
    {
          get { return price; }
          set
          {
           
    if (price == value) return;
            price = value;
            OnPriceChanged (EventArgs.Empty);
          }
        }
      }

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT