Reader Level:
ARTICLE

Learning Delegates in C#, an Introduction

Posted by Matthew Cochran Articles | Visual C# January 03, 2006
There is this thing in C# called a delegate, which is going to be crucial to build interactions between our objects. What’s a delegate, you ask? Good question. A delegate is a pointer to a method. What’s that mean? Just like you can pass variable by reference, you can pass a reference to a method. Let me give you an example.
  • 0
  • 0
  • 38052
Download Files:
 

There is this thing in C# called a delegate, which is going to be crucial to build interactions between our objects. What's a delegate, you ask?  Good question.  A delegate is a pointer to a method.  What's that mean?  Just like you can pass variable by reference, you can pass a reference to a method.  Let me give you an example.

Let's say we have a class with two methods that have the same signature (same return type and same parameter configuration).

public class MyObject
    {
        public int Add(int param1, int param2)
        {
            return param1 + param2;
        }
        public int Multiply(int param1, int param2)
        {
            return param1 * param2;
        }
    }

We can point to either of the methods in our class by using a delegate declared as follows:

public delegate int MyMethodDelegate(int param1, int param2);

Now, if we have another class and want to execute either of the methods in MyObject, we can do it through the delegate as in the "Do()" method in the class below.  As a matter of fact, we can pass any method with the same signature (not JUST the methods in MyObject).  Check out the MySecondObject.Subtract() method. 

public class MySecondObject

     {

          MyObject obj;

          int a, b;

 

          public MySecondObject()

          {

               a=4;

               b=5;

               obj = new MyObject();

          }

 

          public int Do(string pMethod)

          {

               MyMethodDelegate del = null;

 

               switch(pMethod)

               {

                    case"Add":

                         del = new MyMethodDelegate(obj.Add);

                         break;

                    case"Multiply":

                         del = new MyMethodDelegate(obj.Multiply);

                         break;

                    case "Subtract":

                         del = new MyMethodDelegate(this.Subtract);

                         break;

               }

 

               if(null == del) throw new Exception("Not a valid call");

               

               return del(a,b);

          }

 

          public int Subtract(int param1, int param2)

          {

               return param1 - param2;

          }

     } 

Hopefully this gives you a better idea of what delegates are and how they are implemented.
 
Happy coding,

COMMENT USING

Trending up