Delegate the Work
 
Published: 03 Nov 2006
Abstract
Using delegates can add a lot of flexibility to your applications. But hearing this is much different than experiencing the reality of it. In this article we’ll explore how delegates along with events provide loose coupling and make your applications less brittle.
by Stephen Rylander
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22462/ 35

Introduction

A staple of any good management class is pounding into young executives’ heads that they should delegate when possible.  These gurus of commerce do not say to always delegate because it’s obvious that expert knowledge should sometimes directly handle a task or project.  But the premise is solid.  And the premise applies to our world of software.

The .NET Framework provides us with a staid and true mechanism for creating delegates and wiring up events.  It’s a powerful platform provided for free to us, so taking advantage of it is something a developer should aspire to do without much hesitation.  Events are brothers-in-arms with delegates.  They work together so smoothly that you might not even realize that events in the Framework and Windows Forms applications are actually using delegates behind the scenes.

Delegates

Delegates are useful to implement function pointers or callbacks. Here are the basics of a delegate:  Defining a delegate lets you invoke other functions that match the definition of the delegate.  Right – what does that mean?

First off, a delegate is really a class. It derives from System.Delegate (really, it could also derive from System.MulticastDelegate, but we’re trying to keep thing simple here).  So, you can define a delegate and then call it like a method.  See Listing 1.

Listing 1 – Define a delegate

Public delegate bool CookDinner(string MainCourse);

So, what does this get you?  First notice that the delegate looks like a method definition with a return type and method parameters.  That should feel pretty comfortable.  But, like I mentioned above, this is actually getting created as a class, so under the hood it is much more than a method. Now that we have this delegate defined we can use set it up for use.  See Listing 2.

Listing 2 – Setup the delegate

CookDinner cook = new CookDinner(CookingTacos);
 
Private bool CookingTacos(string Meat)
{
  if(Meat != “vegetable”)
   {return true;}
  else
   {return false;}
}

Note that when we initialize the instance of our delegate, CookDinner, with the variable cook we are passing in a method that matches the delegate’s definition to the constructor.  This is very important.  All it takes to instantiate an instance of the delegate is a logical pointer to a method.  Now take a look at Listing 3 and you’ll see how the delegate is used.

Listing 3 – Use the delegate

FeedTheFamily(cook);  //pass in the delegate
Private void FeedTheFamily(CookDinner cookIt)
{
  cookIt(“Beef”);
}

 

This helps us decouple a specific action from each method.  Here, we can pass in our delegate to FeedTheFamily and that method is then able to call the method we already defined.  So now if we decide that FeedTheFamily needs to cook something else, we change the method that is passed in the CookDinner constructor.

Events

Events owe their livelihood to delegates. Before reading this you should understand that delegates allow you to call a method indirectly through the delegate construct.  The focus in discussing events here is not to go into an in depth analysis of invoking and handling different events in Windows Forms and the .NET Framework.   Instead, the focus is to see how delegates and events work together and how you can create and use them to add flexibility and maturity to any type of application.  Let’s take a look at a fresh example.  This example handles events for when a record is read from a database.  See Listing 4.

Listing 4 – Define a new delegate

Here we follow the traditional event programming idiom of passing the object reference of the sender along with an object inheriting from System.EventArgs that contains specific event information. 

Listing 5 – Define the Event

Here we have an event and a method to raise the event.  Both of these are internal to a class named Transform.  The event is defined in terms of the delegate type.  And the method OnRecordRead is called internally, which in turn raises the event up to the event.  Let’s now see how a class hooks this up in Listing 6.

Listing 6 – Application using the event

 

Now we’re really getting somewhere.  What you see in Listing 6 is a class named Client.  Inside of Client a new instance of the class Transform is instantiated.  Next, a handler is wired up to the RecordReadEvent that matches the delegate type of RecordReadEventHandler.  And finally, the method HandlReadRead actually handles the information, or events, that are published.  In essence, Client is acting as a subscriber to the information that Transform is publishing.  Listing 7 below ties these last three diagrams all together.

Listing 7 – Tying it all together

Summary

To summarize this, here are the major parts.

·         Delegate definition

·         Event definition

·         Event publishing

·         Event subscription

·         Event Handling

And what is the beauty of all this?  The fact that it’s easily extendable and usable in your ASP.NET applications, console apps, utilities and smart applications makes it so. It goes way beyond Windows Forms and can add loose coupling and flexibility which is something that object oriented software should strive for.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 1:25:12 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search