C#
  Home arrow C# arrow Page 4 - 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# - Event Accessors


    (Page 4 of 4 )

    An event’s accessors are the implementations of its += and -= functions. By default, accessors are implemented implicitly by the compiler. Consider this event declaration:

      public event EventHandler PriceChanged;

    The compiler converts this to the following:

    • A private delegate field
    • A public pair of event accessor functions, whose implementations forward the+=and-=operations to the private delegate field

    You can take over this process by defining explicit event accessors. Here’s a manual implementation of thePriceChangedevent from our previous example:

      private EventHandler _PriceChanged;     // declare a private delegate

      public event EventHandler PriceChanged
      {
        add
        {
         
    _PriceChanged += value;
        }
        remove
        {
          _PriceChanged -= value;
        }
     
    }

    This example is functionally identical to C#'s default accessor implementation. The add and remove keywords after the event declaration instruct C# not to generate a default field and accessor logic.

    With explicit event accessors, you can apply more complex strategies to the storage and access of the underlying delegate. There are three scenarios where this is useful:

    1. When the event accessors are merely relays for another class that is broadcasting the event.
    2. When the class exposes a large number of events, where most of the time very few subscribers exist, such as a Windows control. In such cases, it is better to store the subscriber’s delegate instances in a dictionary, since a dictionary will contain less storage overhead than dozens of null delegate field references.
    3. When explicitly implementing an interface that declares an event.

    Here is an example that illustrates the last point:

      public interface IFoo
      {
       
    event EventHandler Ev;
      }

      class Foo : IFoo
      {
       
    private EventHandler ev;

        event EventHandler IFoo.Ev
       
    {
         
    add    { ev += value; }
         
    remove { ev -= value; }
       
    }
      }

    Theaddandremove parts of an event are compiled toadd_XXX  andremove_XXX methods.

    The+=and-=operations on an event are compiled to calls to theadd_XXX andremove_XXX methods.

    Event Modifiers

    Like methods, events can be virtual, overridden, abstract, and sealed. Events can also be static:

      public class Foo
      {
        public static event EventHandler<EventArgs>StaticEvent;
        public virtual event EventHandler<EventArgs>VirtualEvent; 
      }

    Please check back next week for the continuation of this article.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 3 hosted by Hostway
    Stay green...Green IT