This is a mirror of official site: http://jasper-net.blogspot.com/

Internals of a Delegate

| Monday, December 27, 2010
Strange Rules of Delegate

Well, at recent times, at least after the introduction of .NET framework 3.5 the use of Delegates in a program has increased quite a bit. Now almost every people in .NET language must at least somehow used delegates on their daily programming activities. It might be because of the fact that the use of delegates has been simplified so much with the introduction of lambda expressions in .NET framework 3.5 and also the flexibility to pass delegates over other libraries for decoupling and inversion of control in applications. Hence, we can say the way of writing code in .NET environment has been changed considerably in recent times.

Introduction

If you want the most simple and somewhat vague idea about delegates I would say a delegate is actually a reference to a method so that you might use the reference as you use your object reference in your code, you can send the method anywhere in your library or even pass to another assembly for its execution, so that when the delegate is called, the appropriate method body will get executed. Now, to know a more concrete and real life example, I must consider you to show a code :

public delegate int mydelegate(int x);
       public class A
       {
           public mydelegate YourMethod { get; set; }

           public void ExecuteMe(int param)
           {
               Console.WriteLine("Starting execution of Method");
               if (this.YourMethod != null)
               {
                   Console.WriteLine("Result from method : {0}", this.YourMethod(param));
               }
               Console.WriteLine("End of execution of Method");
           }
       }
       

       static void Main(string[] args)
       {

           //int x = 20;
           //int y = 50;

           A a1 = new A();

           a1.YourMethod = Program.CallMe;


           a1.ExecuteMe(20);

           Console.Read();
   }
    public static int CallMe(int x)
       {
           return x += 30;
       }

}

In the above code, I have explicitly declared a delegate and named it mydelegate. The name of the delegate will indicate that it is a type that can create reference to a method which can point to a method which have same signature as defined in it. Clearly If you quickly go through the code defined above, the property YourMethod can point to a signature which has same signature as declared to mydelegate. Hence, I can pass a method CallMe easily to Type A, so that when the object of A calls the delegate, it executes the method CallMe.

Read more: DOT NET TRICKS

Posted via email from .NET Info

0 comments: