Resources / C# / Using Delegates a simple example /
Select CategoryEnter KeywordsSearch
Search {27416} Articles (Last Index: 11/03/2010 06:03:54)
Using Delegates a simple example
Subscribe Bookmark and Share

Using Delegates a simple example

This example has three delegate examples.  These are encapsulated by the Classes DelegatDemo, Delegate Demo1 and DelegateDemo2.

What is a delegate

Just like its name implies it is a form of delegation ie delegating work to something that will do a piece of work.  In this case we use another object (a delegate)  to run a method or methods for us.

These are basically function pointers or another name for them is Functors.  They do exactly that point to functions stored in memory and when they are called run those functions.  These are commonly used in event handling as we will see a little later on and are used by Microsoft components on Windows forms for event handling.

  1. New Delegate Object created at memory location
  2. Function doThis() placed in d reference
  3. When d() called runs functions found in d

First Example – DelegateDemo

{

    delegate String DelegateAbc(String txt);

   

    class DelegateDemo

    {

       //delegate String DelegateAbc(String txt);

 

        public String TestAbc(String txt)

        {

            Console.WriteLine(txt);

            return "DeleteDemo..........Hello from TestAbc";

        }

       

        public static String TestStatic(String txt)

        {

            Console.WriteLine(txt);

            return "DeleteDemo..........Hello from TestStatic";

        }

 

    }

 

Notice first that the delegate can be declared as a class on its own outside the class we are creating as delegates are classes.  They can also be declared inside the class either will work we have chosen to put it outside makes it more flexible if it is to be used by any other classes or objects.

This delegate will take any methods that return a String (take care here as usually it is wise not to have returns from delegates especially if you are going to multicast – see later) and takes a String as a parameter.

Inside the class we simply have one instance method and one static method.

The following method is in the main method and is used to run this class.

public static void runDelegateDemo()

        {

            DelegateDemo t1 = new DelegateDemo();

            //Create a new delegate and pass in instance method TestABC

            DelegateAbc d1 = new DelegateAbc(t1.TestAbc);

            Console.WriteLine("");

            Console.WriteLine("");

            //Now pass in the static method TestStatic to delegate

            Console.WriteLine(d1("DeleteDemo..........First call coming

from within delegated procedure"));

            d1 = new DelegateAbc(DelegateDemo.TestStatic);

            Console.WriteLine(d1("DeleteDemo..........Second call coming

from within delegated procedure"));

            Console.WriteLine("");

            Console.WriteLine("");

        }

 

First we create a new delegate object d1 and add the instance method t1.TestABC into it.  Then we call the delegate d1 inside a WriteLine statement passing the text argument ("DeleteDemo..........First call coming from within delegated procedure"into it.

We then create a new delgate object and place the static method inside it.  We then call the delegate d1 inside the next WritLine statement passing the text "DeleteDemo..........Second call coming from within delegated procedure".

Output from runDelegateDemo()

DeleteDemo..........First call coming from within delegated procedure
DeleteDemo..........Hello from TestAbc
DeleteDemo..........Second call coming from within delegated procedure
DeleteDemo..........Hello from TestStatic

As you may have expected the instance method is run first followed by the static method…..

Second Example – DelegateDemo1

delegate void DelegateAbc1();

  

    class DelegateDemo1

    {

        //delegate void DelegateAbc1();

 

        public void TestAbc()

        {

            Console.WriteLine("DelegateDemo1..........

This is from TestAbc");

        }

        public static void TestStatic()

        {

            Console.WriteLine("DelegateDemo1..........

This is from the static method");

        }

 

    }

 

Again we have an instance method and a static method both that match the signature and return type of the delegate … NO return and NO argument.

To run this we have the procedure outlined below:

static void runDelegateDemo1()

        {

            DelegateDemo1 t1 = new DelegateDemo1();

            //Create new delegate d1 put in instance method TestABC

            DelegateAbc1 d1 = new DelegateAbc1(t1.TestAbc);

            //Create new delegate d2 put in static method TestStatic

            DelegateAbc1 d2 = new DelegateAbc1(DelegateDemo1.TestStatic);

            Console.WriteLine("");

            Console.WriteLine("");

           

            //Add d2 to d1

            d1 = d1 + d2;

            Console.WriteLine("DeleteDemo1..........About to make First call");

            //Run delegate d1

            d1();

            //Take out d2 from d1

            d1 -= d2;

            Console.WriteLine();

            Console.WriteLine("DeleteDemo1..........About to make Second call");

            //Run d1 again

            d1();

            Console.WriteLine("");

            Console.WriteLine("");

        }

 

Here we create 2 objects of the type DelegateDemo1, d1 and d2. In d1 we put in the instance method t1.TestAbc() and in d2 we put in the static method  DelegateDemo1.TestStatic().  Note both methods’ signature and return match those of the delegates.

What we show here is that we can create a list of methods or functions inside a delegate so when it is called it will run all of the methods it finds that are being delegated.  Here we are using the shortcut operator += to add the method in d2 to the one in d1.  So d1 now has a pointer to both methods. 

When we call the delegate with the command d1(); It runs both methods.

We then use the shortcut operator -= to take out any methods that are contained in d2 from d1, so we should now be left with just the instance method in d1.

When we call the delegate with the command d1(); This time it runs just the instance method.

Output from runDelegateDemo1()


DeleteDemo1...............About to make First call
DelegateDemo1..........This is from TestAbc
DelegateDemo1..........This is from the static method

DeleteDemo1...............About to make Second call
DelegateDemo1..........This is from TestAbc.

 
Third Example – DelegateDemo2

delegate int DelegateAbc2(int i);

 

    class DelegateDemo2

    {

        //delegate int DelegateAbc2(int i);

 

        public int SquareMe(int i)

        {

            return i * i;

        }

        public int CubeMe(int i)

        {

            return i * i * i;

        }

         public void ShowResult(DelegateAbc2 d, String s, int i)

        {

            Console.WriteLine("{0} of {1} is {2}", s, i, d(i));

        }

 

      

 

    }

Here we have a delegate that returns an int and takes an int as a parameter.

We create 2 instance methods with the same return types and parameters as the delegate.  One quite obviously squares a number the other cubes it.

We then create an instance method that takes a delegate type, a String and an int as its parameters.

Note it will print the String …’of’ int… ‘is’ the result from the delegate call.

 To run this we have the procedure outlined below:

  static void runDelegateDemo2()

        {

            DelegateDemo2 t = new DelegateDemo2();

            Console.WriteLine("");

            Console.WriteLine("");

            Console.WriteLine("DeleteDemo2..........First call to

show result passing in SquareMe as DelegateABC2");

            t.ShowResult(new DelegateAbc2(t.SquareMe), "Square", 7);

            Console.WriteLine("");

            Console.WriteLine("");

            Console.WriteLine("DeleteDemo2..........Second call to

show result passing in CubeMe as DelegateABC2");

 

            t.ShowResult(new DelegateAbc2(t.CubeMe), "Cube", 7);

        }

 

We create a new instance of DelegateDemo2 called t. First we run the instance method t.ShowResults passing across the delegate with the method t.SquareMe inside it (as well as the String “Square” and the int 7).  Then we run t. ShowResults passing across the delegate with the method t.CubeMe inside it (as well as the String “Cube” and the int 7). 


Output from runDelegateDemo2()

DeleteDemo2..........First call to show result passing in SquareMe as DelegateAB
C2
Square of 7 is 49


DeleteDemo2..........Second call to show result passing in CubeMe as DelegateABC
2
Cube of 7 is 343
  

Written By Pete Apostolou [http://www.itprotraining.com]

Keywords:
delegates, c#

Return to previous page

Attachments
FileExtensionSize (bytes)Modified Date
Delegates1.zip.zip2800917/03/2009 14:15:59
Send to a friend
Add Your Comments

You are not currently logged on.
You must be a registered member to comment on our resource pages.

It is free to register. You can register here Registration Form

Login / Register
Popular Tags
Description

Resources

C# | Visual Basic | ASP.Net | SQL | CSS | XML | Java Script | AJAX | UML | Python | Perl | PHP | Oracle | MySql | Sybase | LINQ | Struts | Sharepoint | J2EE | Java | Mobile | .NET | Ruby | DB2 | DirectX | Silverlight | C++ | 

Courses

VB.Net | 

Company

Terms of Service | Advertising | Privacy Policy | Content Provider Agreement | Open Licence | 

Site Map (Visual) | Site Map

Copyright © 2008 Learn How To Program. All rights reserved.