C#
  Home arrow C# arrow 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#


    (Page 1 of 4 )

    In this second part of a ten-part series that focuses intensely on C#, we will wrap up our discussion of delegates, then move on to one of the most important subjects in the language: events. 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). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    Delegate Compatibility

    Type compatibility

    Delegate types are all incompatible with each other, even if their signatures are the same:

      delegate void D1();
      delegate void D2();
      ...

      D1 d1 = Method1;
      D2 d2 = d1;                       // compile-time error

    Delegate instances are considered equal if they have the same method targets:

      delegate void D();
      ...

      D d1 = Method1;
      D d2 = Method1;
      Console.WriteLine (d1 == d2);    // true

    Parameter compatibility

    When you call a method, you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exactly the same reason, a delegate can have more specific parameter types than its method target. This is called contravariance.

    Consider the following example:

      delegate void SpecificDelegate (SpecificClass s);

      class SpecificClass {}

      class Test
      {
        static void Main()
        {
          SpecificDelegate specificDelegate = GeneralHandler;
          specificDelegate (new SpecificClass());
        }

        static void GeneralHandler(object o)
        {
          Console.WriteLine(o.GetType()); // SpecificClass
        }
      }

    A delegate merely calls a method on someone else’s behalf. In this case, theSpecificDelegateis invoked with an argument of typeSpecificClass. When the argument is then relayed to the target method, the argument gets implicitly upcast to anobject.

    The standard event pattern is designed to help you leverage contravariance through its use of the commonEventArgsbase class. For example, you can have a single method invoked by two different delegates, one passing aMouseEventArgsand the other passing aKeyEventArgs.

    Return type compatibility

    If you call a method, you may get back a type that is more specific than what you asked for. This is ordinary polymorphic behavior. For exactly the same reason, the return type of a delegate can be less specific than the return type of its target method. This is called covariance. Consider the following example:

      delegate Asset DebtCollector();

      class Asset {}

      class House : Asset {}

      class Test
      {
        static void Main()
        
    {
          DebtCollector d = new DebtCollector (GetHomeSweetHome);
          
    Asset a = d();
         
    Console.WriteLine(a.GetType()); // House
       
    }
        
    static House GetHomeSweetHome() {return new House(); }
      }

    A delegate merely calls a method on someone else’s behalf. In this case, theDebtCollectorexpects to get back anAsset—but anyAssetwill do. Delegate return types are said to be covariant.

    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

    - 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#
    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...





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