Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

DelegateTypeT makes using delegates a breeze!

0.00/5 (No votes)
17 Feb 2006 2  
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:

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:

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.

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

Step 2: Add your delegate handlers.

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

Step 3: Invoke the delegate procedures.

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).

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

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

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:

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