June 27, 2008
Hi Guys
NP104 Why is rule not followed1?
It should be like this:
AddBookEventHandler bookShop.AddBook +=
new AddBookEventHandler(notify.instance_AddBook);
But in the following program it is like this:
bookShop.AddBook +=
new AddBookEventHandler(notify.instance_AddBook);
But program is executing well.
Please explain the reason.
Thank you
using System;
using System.Collections;
namespace Events
{
public delegate void AddBookEventHandler(object source, BookEventArgs e);
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 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);
}
}
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 Members\n" + " regarding the book '{0}' with the ISBN '{1}'\n", e.Book.Title, e.Book.ISBN);
}
}
//The Sys Class is the application that uses all the above classes.
//Let's look at the code:
public class Sys
{
public static void
{
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();
}
}
}
Posted Jun 27, 2008, 5:20 PM
Thank you for your explanation, Ryan Alford
Ryan AlfordPosted Jun 27, 2008, 5:08 PM
So no, it should not be an AddBookEventHandler. The code is correct just like it is.