Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / Windows Forms
Article

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 31.5K   17   7
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


Written By
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 19:28
rama dadi8-May-06 19:28 
GeneralEventHandler Pin
John Fisher17-Feb-06 11:18
John Fisher17-Feb-06 11:18 
GeneralRe: EventHandler Pin
Tim Speekenbrink17-Feb-06 21:31
Tim Speekenbrink17-Feb-06 21:31 
Hi John,
Thanks for even taking time to read this. I do know about the Eventhandler, but didn't really about the generic type.
My reason for using a delegate type was more the mind than anything else.
I associate events more with something happening outside my program scope (like a user clicking a button) and delegates more like an internal mechanism.

But yes, they could both be used equally, I guess.

Tim

Where is the glue that glues together all the code snippets on The CodeProject to the ultimate solution, so I never have to work anymore?
GeneralRe: EventHandler Pin
John Fisher22-Feb-06 6:30
John Fisher22-Feb-06 6:30 
GeneralRe: EventHandler Pin
Will Gray22-Feb-06 2:28
Will Gray22-Feb-06 2:28 
GeneralRe: EventHandler Pin
John Fisher22-Feb-06 6:28
John Fisher22-Feb-06 6:28 
GeneralRe: EventHandler Pin
Tim Speekenbrink22-Feb-06 21:24
Tim Speekenbrink22-Feb-06 21: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.