SunQuest
 
       C#
  Home arrow C# arrow Page 4 - C# Events Explained
Iron Speed
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 
Dedicated Servers 
Actuate Whitepapers 
VeriSign Whitepapers 
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#

C# Events Explained
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 41
    2007-02-13

    Table of Contents:
  • C# Events Explained
  • The Windows Form Example
  • The Steps of Creating an Event
  • The Bookshop Class and the AddBookEventHandler Delegate
  • The Notifier and the Sys Classes
  • Event Without an Event

  • 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

    At the virtual BlackBerry Technical Seminar 2008, you can ask your development questions directly of Research In Motion® (RIM) experts, and take advantage of learning opportunities designed uniquely for BlackBerry solution developers. Register Today!

    C# Events Explained - The Bookshop Class and the AddBookEventHandler Delegate


    (Page 4 of 6 )

    Let's first create the delegate:

    public delegate void AddBookEventHandler(object source, BookEventArgs e);

    The delegate encapsulates any method that takes two parameters, an object and a BookEventArgs instance, and returns void. Note that the BookEventArgs class, which is implemented in the next section, derives the EventArgs class. When you need to carry data for the event you must create a class that derives the EventArgs class. Next, let's look at the implementation of the BookShop class.

    public class BookShop
    {
      private ArrayList books;
      private string name;
      public event AddBookEventHandler AddBook;

      public BookShop(string name)
      {
        books = new ArrayList();
        this.name = name;
      }

      protected void OnAddBook(BookEventArgs e)
      {
        if(AddBook != null)
          AddBook(this, e);
      }

      public void AddNewBook(Book book)
      {
        this.books.Add(book);
        BookEventArgs e = new BookEventArgs(book);
        OnAddBook(e);
      }
    }

    The Bookshop class contains a private ArrayList to store the books, but the interesting code begins with the declaration of the event. We have declared an event called AddBook of type AddBookEventHandler delegate with the event keyword. Why do we need to do this?

    1. When you define an event as of a specific delegate type you standardize the signature of the methods that can be notified (through delegates) of the occurrence of that particular event.
    2. Also the event creates a multicast delegate (of the delegate type it has been declared with). To maintain the assigned delegates of the watcher objects, you assign a delegate instance to a multicast delegate through the += operator.

    The method OnAddBook() raises the AddBook event. It simply checks if the multicast delegate of the event is not null then calls the delegate using the event identifier. The method AddNewBook(), which calls the OnAddBook() method, accepts a Book instance as a parameter, then it adds the instance to the private ArrayList object. The method creates a new instance of the class BookEventArgs and passes the Book instance to the constructor. Then it calls the OnAddBook() method and passes the BookEventArgs instance to it.

    As we said, the OnAddBook() method raises the event by invoking the multicast delegate. The signature of the delegate takes two parameters: the first is of type object which represents the object that raised the event and that's why we passed the this keyword and the second is the BookEventArgs instance, which is created by AddNewBook() then passed to OnAddBook() method, which passes it to the multicast delegate:

    AddBook(this, e);

    Client code should call the AddNewBook() method which in turn calls the method OnAddBook() that raises the event.

    The BookEventArgs Class

    The BookEventArgs class derives the EventArgs class. It contains data (the Book object newly added to the bookshop) for the event. Imagine that you subscribed to the AddBook event but you don't have access to the newly created Book instance inside the event handler method.  I don't want to imagine something like that anyway. Here's the code of the class:

    public class BookEventArgs: EventArgs
    {
      private Book book;
      public BookEventArgs(Book book)
      {
        this.book = book;
      }

      public Book Book
      {
        get { return this.book;}
      }
    }

    This class is passed the Book instance when it's created in the BookShop.AddNewBook() method so there's nothing special here. It takes the Book instance and stores it in a private field. You can read the object through the public property.

    More C# Articles
    More By Michael Youssef


       · I work with C# for 9 months now and I couldn't understand events until I read your...
       · I always liked Michael intuitive writing style about various .NET topics and this...
       · Thanks for your comments about my article. Actually, each and every one of us who...
       · Mr.Michael I haven't read any of your articles and my first one was C# events. I'm...
       · I'm happy that you liked my articles and yes I plan to write about ASP.NET 2.0 very...
       · I work with different programming languages, and never meet such understanddable...
       · Glad you liked my articles. Could you please tell me what are those topics you want...
       · First, fantastic article. The best explanation of events that I have read to...
       · Hi,Thanks for your comment, I tried to do my best explaining those basics to...
       · Thanks Michael,That is what I was asking. I did not realise that there would...
       · You are welcome
       · Excellent article as well as the article on delegates which is a must read. Can you...
       · Thanks, I hope I can write more articles about C# soon. Anyway, I'm writing more...
       · You might also want to read my articles about C# Properties and Indexers. You will...
     

    C# ARTICLES

    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...
    - Polymorphism in C#
    - Inheritance in C#
    - C# Events Explained
    - C# Delegates Explained
    - C# StreamReader and StreamWriter Explained
    - C# FileStream Explained

    Iron Speed




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway