C#
  Home arrow C# arrow Page 6 - C# Events Explained
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#

C# Events Explained
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 46
    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


    C# Events Explained - Event Without an Event


    (Page 6 of 6 )

    I have modified the example to remove the event and to use the delegate only to fire the event. Here's the code:

    using System;
    using System.Collections;

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

      public class BookShop
      {
        private ArrayList books;
        private string name;

        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);
        }

        private AddBookEventHandler addBook;
        public AddBookEventHandler AddBook
        {
          get{return addBook;}
          set {addBook = value;}
        }
      }

      public class Book
      {
        private string title;
        private string isbn;
        private decimal price;

        public Book(string title, string isbn, decimal price)
        {
          this.title = title;
          this.isbn = isbn;
          this.price = price;
        }

        public string Title
        {
          get{return this.title;}
        }
        public string ISBN
        {
          get{return this.isbn;}
        }
        public decimal Price
        {
          get{return this.price;}
        }
      }

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

        public Book Book
        {
          get { return this.book;}
        }
      }
      public class Notifier
      {
        public void instance_AddBook(object source, BookEventArgs e)
        {
          Console.WriteLine("A Message has been sent to the Membersn" + " about the book '{0}' with the ISBN '{1}'n", e.Book.Title, e.Book.ISBN);
          //((BookShop)source).AddBook = null;
        }
      }

      public class Sys
      {
        public static void Main()
        {
          BookShop bookShop = new BookShop(".NET Bookshop");

          Book b1 = new Book("The Right Way","123456789", 19.90m);
          Book b2 = new Book("The .NET Stuff","987654321", 29.90m);

          Notifier notify = new Notifier();

          bookShop.AddBook =
            new AddBookEventHandler(notify.instance_AddBook);

          bookShop.AddNewBook(b1);
          bookShop.AddNewBook(b2);
          Console.ReadLine();
        }
      }
    }

    Run the code and you will have the same results. Now uncomment the last statement in the instance_AddBook() method and run the application again.

    Only the event-like mechanism fires for the first book added to the bookshop; it didn't fire for the next time a book is added. We were able to set the value of the Multicast delegate to null in the watcher class by casting the source object (which is the BookShop instance that fired the event) to BookShop, then assigned a null value to the property AddBook. By assigning a null value to the AddBook property we remove the other subscribed event handler methods, causing the event to stop functioning. Also now you can use the = instead of += operator to assign a delegate to the multicast delegate, which also is not valid because the event should adds on its multicast delegate, not replace it. 

    What we have done in the above application is remove the event from the BookShop class then create a private field of delegate type AddBookEventHandler and its public property. This property is used to assign a AddBookEventHandler delegate instance to the private field addBook. The method OnAddBook() raises the event by calling the delegate through the AddBook property. In the Sys class we assign a new AddBookEventHandler delegate instance to the AddBook property using the Assignment operator. The event is raised but because AddBook is a public property we have the ability to assign any new value to it outside the BookShop instance as we did in the event handler method and set null value to this property. So when we use this mechanism we define AddBook as a property.

    But with the event model we define it as an event which has restrictions

    As you can see, the event is very similar to the property that we created but with restrictions. To understand this better take the following statement and place it at the end of the Notifier class' event handler method of the event example (not the event without an event section) then try to compile the code.

    ((BookShop)source).AddBook = null;

    The code will not compile and you will get the following error:

    It says that you can't use the AddBook event except as the left hand side of += or -= operations outside the BookShop. I hope that by now you understand how events are created and what the difference is between using an event and a delegate.


    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.

       · 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...
       · That was a good read...
       · one of the most clearly explained articles I have read this year. Thank you very...
       · Hi all,Thank you so much for your posts, .NET Windows Forms technology is based...
     

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