15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

summary ❘ 205<br />

}<br />

}<br />

public void NewCarIsHere(object sender, CarInfoEventArgs e)<br />

{<br />

Console.WriteLine("{0}: car {1} is new", name, e.Car);<br />

}<br />

bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender,<br />

EventArgs e)<br />

{<br />

NewCarIsHere(sender, e as CarInfoEventArgs);<br />

return true;<br />

}<br />

code snippet WeakEventsSample/Consumer.cs<br />

Inside the Main method where the publisher <strong>and</strong> listeners are connected, the connection is now done<br />

by using the static AddListener() <strong>and</strong> RemoveListener() methods from the WeakCarInfoEvent<br />

Manager class.<br />

static void Main()<br />

{<br />

var dealer = new CarDealer();<br />

var michael = new Consumer("Michael");<br />

WeakCarInfoEventManager.AddListener(dealer, michael);<br />

dealer.NewCar("Mercedes");<br />

var nick = new Consumer("Nick");<br />

WeakCarInfoEventManager.AddListener(dealer, nick);<br />

dealer.NewCar("Ferrari");<br />

WeakCarInfoEventManager.RemoveListener(dealer, michael);<br />

}<br />

dealer.NewCar("Toyota");<br />

code snippet WeakEventsSample/Program.cs<br />

With this additional work of implementing the weak event pattern, the publisher <strong>and</strong> listeners are no longer<br />

strongly connected. When a listener is not referenced anymore, it can be garbage collected.<br />

summary<br />

This chapter gave you the basics of delegates, Lambda expressions, <strong>and</strong> events. You learned how to declare<br />

a delegate <strong>and</strong> add methods to the delegate list. You learned how to implement methods called by delegates<br />

with Lambda expressions. You also learned the process of declaring event h<strong>and</strong>lers to respond to an event,<br />

as well as how to create a custom event <strong>and</strong> use the patterns for raising the event.<br />

As a .<strong>NET</strong> developer, you will be using delegates <strong>and</strong> events extensively, especially when developing<br />

Windows applications. Events are the means that the .<strong>NET</strong> developer has to monitor the various Windows<br />

messages that occur while the application is executing. Otherwise, you would have to monitor the WndProc<br />

<strong>and</strong> catch the WM_MOUSEDOWN message instead of getting the mouse Click event for a button.<br />

The use of delegates <strong>and</strong> events in the design of a large application can reduce dependencies <strong>and</strong> the<br />

coupling of layers. This allows you to develop components that have a higher reusability factor.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!