Click here to Skip to main content
15,122,406 members
Articles / Desktop Programming / Windows Forms
Article
Posted 17 Feb 2006

Stats

30.4K views
17 bookmarked

DelegateTypeT makes using delegates a breeze!

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
17 Feb 20063 min read
DelegateTypeT, a wrapper class for delegates, with a simple usage.

Introduction

The DelegateTypeTClass provides a simple and easy to understand mechanism to work with delegates.

Background

There are already many articles on delegates and events. Some better, some less understandable. Anyway, trying to implement a simple delegate queue took me flipping back and forth between my own code and the articles, trying to understand what needs to be done and in what order. As I needed to be able to use a dynamic queue of methods to perform operations on the same set of data, I decided to use the nice Generics feature of .NET 2.0, and implement a generic delegate class that handles the specifics for me. I also think that this class implementation shows a nice, short sample on how to use delegates.

Using the code

To use the DelegateTypeTClass, just add a using directive for DelegateTypeT, or just include the sourcefile DelegateTypeT.cs.

The included demo program shows exactly how this all works. But let me tell you anyway:

Suppose you create a program that needs to process some list of strings in several different ways, but that this processing might change in the future. You code the processors you need now, and could just call them sequentially in your code. However, when you need to add a new processing step, you would have to change the main program to include the new processing step. This is where delegates come to the rescue.

In simple terms, a delegate is just a list of methods that each need to be called with the same (kind of) input.

So by using delegates, your new processing class would just have to add itself to that delegate list.

The demo program uses two processors for a list of strings. The first just prints the list to the console, the second processor prints the length of each string:

C#
static void Processor1(List<STRING> input)
{
    foreach (string ST in input)
    {
        Console.WriteLine(ST);
    }
}

static void Processor2(List<STRING> input)
{
    foreach (string ST in input)
    {
        Console.WriteLine(ST.Length);
    }
}

Note: they don't need to be static, I just was lazy writing up the demo program!

The demo program needs to write the following information to the console:

C#
List<STRING> test = new List<STRING>(args);
test.Add("This shows a test using the DelegateTypeTClass");
test.Add("May be this makes it easier to use and understand the");
test.Add("concept of delegates!");
test.Add("The list of string lengths is displayed twice, to showthe");
test.Add("removal of processors from the delegate queue)");

This prints all strings in this list, the length of each string, and then again only the list of lengths.

Using DelegateTypeTClass, this involves only three easy steps:

Step 1: Create an instance with the required type.

C#
DelegateTypeT.DelegateTClass<LIST<STRING>> MyProcessors = 
            new DelegateTypeT.DelegateTClass<LIST<STRING>>();

Step 2: Add your delegate handlers.

C#
MyProcessors.Add(Processor1);
MyProcessors.Add(Processor2);

Step 3: Invoke the delegate procedures.

C#
MyProcessors.InvokeDelegates(test);

And that is all there is to it!

The demo program, however, needs to print the list of lengths twice, and as we are showing the dynamic nature of delegates, we remove the first processor (the one that prints the strings) and invoke the delegates again (which then only contains Processor2).

C#
MyProcessors.Remove(Processor1);
MyProcessors.InvokeDelegates(test);

Of course, you can also do this 'the old fashioned way':

C#
MyProcessors.DelegatesToInvoke += 
    new DelegateTypeT.DelegateTClass<LIST<STRING>>.DelegateSignature(Processor1);

And equally use the -= operator to remove.

The code in the class is pretty straightforward, and is listed here for convenience:

C#
using System;
using System.Collections.Generic;
using System.Text;

namespace DelegateTypeT
{
    /// <SUMMARY>
    /// A generic Multicast Delegate handling class
    /// provides an easy interface for working with delegates
    /// i.e. use a list of methods to process some data or 
    /// perform some functions
    /// This class handles only one parameter in the method signature
    /// <TYPEPARAM name="T"></TYPEPARAM>
    /// </SUMMARY>
    public class DelegateTClass<T>
    {
        /// <SUMMARY>
        /// Define the method signature
        /// </SUMMARY>
        /// <PARAM name="input"></PARAM>
        public delegate void DelegateSignature(T input);
        /// <SUMMARY>
        /// The delegates invocation list, used as:
        /// DelegateTClass.DelegatesTo Invoke += new
        ///      DelegateTClass<T>.DelegateSignature(Check2)
        /// To discourage use defined as private
        /// Or: DelegateTypeTClass.Add(methodname)
        /// </SUMMARY>
        public DelegateSignature DelegatesToInvoke;
        /// <SUMMARY>
        /// Execute the delegates in the order added to DelegatesToInvoke
        /// </SUMMARY>
        /// <PARAM name="input"></PARAM>
        public void InvokeDelegates(T input)
        {
            DelegatesToInvoke(input);
        }
        /// <SUMMARY>
        /// Constructor
        /// </SUMMARY>
        public DelegateTClass() {}

        /// <SUMMARY>
        /// Add a method to the DelegatesToInvoke list by just
        /// referencing the method name
        /// For Instance: MyDelegate = new DelegateTypeTClass(List<STRING>)
        ///               void  MyProcessor(List<STRING> line)
        ///                         { Console.Writeline(line); }
        ///               MyDelegate.Add(MyProcessor);
        /// </SUMMARY>
        /// <PARAM name="P"></PARAM>
        public void Add(DelegateSignature P)
        {
            DelegatesToInvoke += P;
        }
        public void Remove(DelegateSignature P)
        {
            DelegatesToInvoke -= P;
        }
    }
}

History

This is my first article as a give back for all the examples and code I used from CodeProject to teach myself C#. I must have been the biggest downloader.

Please send me your critique, that's how I can learn!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Tim Speekenbrink
Web Developer
Netherlands Netherlands
After being more then 30 years in the computer science starting as an assembler programmer, I finally have some time to start learning some windows programming and thus my first steps into the Onbject Oriented technology. I am glad C# is easy to learn. Just finding the objects and classes you need to perform just that what you want is still a nightmare. But we will get there.
My memory i snot as good anymore as it used to be, so I try to write simple to use wrappers around difficult to remember code.
Being most of my career in second lever support of software I can read any code in any computer language, but writing good code is quite another ballgame!

Comments and Discussions

 
QuestionHow to GetObjects Pin
rama dadi8-May-06 20:28
Memberrama dadi8-May-06 20:28 
GeneralEventHandler Pin
John Fisher17-Feb-06 12:18
MemberJohn Fisher17-Feb-06 12:18 
GeneralRe: EventHandler Pin
Tim Speekenbrink17-Feb-06 22:31
MemberTim Speekenbrink17-Feb-06 22:31 
GeneralRe: EventHandler Pin
John Fisher22-Feb-06 7:30
MemberJohn Fisher22-Feb-06 7:30 
GeneralRe: EventHandler Pin
Will Gray22-Feb-06 3:28
MemberWill Gray22-Feb-06 3:28 
GeneralRe: EventHandler Pin
John Fisher22-Feb-06 7:28
MemberJohn Fisher22-Feb-06 7:28 
Will Gray wrote:
I think of events as being more for multithreaded applications and used to tell other objects that something happened so they can execute some code in response.


EventHandler<> is a delegate. An event is what you get when you use the delegate with the "event" keyword. You could turn the delegate from this article into events, too. In relation to being an event, neither EventHandler nor the delegates discussed in this article are any different.

Will Gray wrote:
I think this is an excellent use of delegates.


Clearly, it is a good idea, since almost everyone uses it as implemented by EventHandler<>. The significant difference between that and the content of this article is the existence of the "object sender" in the delegate signature.

John

"You said a whole sentence with no words in it, and I understood you!" -- my wife as she cries about slowly becoming a geek.

GeneralRe: EventHandler Pin
Tim Speekenbrink22-Feb-06 22:24
MemberTim Speekenbrink22-Feb-06 22:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.