Delegates

TAKEN FROM C# In Depth Third Edition 

A delegate in C# acts like your will does in the real world – it allow you to specify a sequence of actions to be executed at the appropriate time.

In order for a delegate to do anything, four things need to happen:

  • The delegate type needs to be declared
  • The code to be executed must be contained in a method
  • A Delegate instance must be created
  • The delegate instance must be invoked

The delegate type needs to be declared

Consider a delegate type declared like this:

delegate void StringProcessor (string Input)

The code to be executed must be contained in a method

We then need to find an appropriate method to match that signature

void PrintString(string x)

But the following doesn’t match

void PrintInteger(int x)

So we can’t use it.

A Delegate instance must be created

Now create a delegate instance

StringProcessor proc1, procc2;
proc1 = new StringProcessor(StaticMethods.PrintString);
InstanceMethods instance = new InstanceMethods();
proc2 - new StringProcessor(instance.PrintString);

The delegate instance must be invoked

Its easier to show this in an example

namespace Chapter02
{
    delegate void StringProcessor(string input);
    class Person
    {
        string name;

        public Person(string name)
        {
            this.name = name;
        }

        public void Say(string message)
        {
            Console.WriteLine("{0} says: {1}", name, message);
        }
    }

    class Background
    {
        public static void Note(string note)
        {
            Console.WriteLine("({0})", note);
        }
    }

    [Description("Listing 2.1")]
    class SimpleDelegateUse
    {
        static void Main()
        {
            Person jon = new Person("Jon");
            Person tom = new Person("Tom");

            StringProcessor jonsVoice, tomsVoice, background;
            jonsVoice = new StringProcessor(jon.Say);
            tomsVoice = new StringProcessor(tom.Say);
            background = new StringProcessor(Background.Note);

            jonsVoice("Hello, son.");
            tomsVoice.Invoke("Hello, Daddy!");
            background("An airplane flies past.");
        }
    }
}

The output from the above is

Jon says: Hello, son.
Tom says: Hello, Daddy!
An airplane flies past.

TAKEN FROM C# In Depth Third Edition 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s