Saturday, May 26, 2012

An Introduction to Delegates in C#

If you are familiar with Function Pointers in C or C++ and if you are wondering is there something similar to Function Pointers in C#, Of course there is. It's Delegates. Delegates in one of the nicest techniques in C#, but some find hard to understand the real beauty behind it. So thought to write an Introduction about delegates in C#.

Basically a delegate is a type that references a method or methods. A delegate defines a method signature, and it has the capability of referencing to a methods/methods which has the same method signature as in the delegate. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. Then you can invoke the method through the delegate instance. What really happens here is delegate encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Because of this behavior, delegates gives us many advantages. One thing is you can pass methods as arguments to other methods. Second is since we are using delegate to invoke the method, it will hide the method from the caller. Another nice advantage would be, using delegates we can call methods asynchronously.

Now let's see delegates in action. First, this is how we define delegates.
public delegate void MyDelegate(string s);
What this delegate means is, it has the capability to encapsulate any method that takes one string value and returns no value. Always remember delegates only has the capability to refer methods in which return type matches delegates return type and parameters matches delegates parameters.

Now let's take this simple but full example.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyMethod(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}
Output :

calling a method through adelegate

In here I have defined a namespace level delegate, so it as accessible from all the classes in namespace. I have created two classes here to make it easy to understand. In "MyClass", I have wrote a method in which method signature is same as the delegate. Then from my Main method, I have created an instance of "MyClass", so I can access it's methods. Then I am creating an instance of "MyDelegate", and I am passing the method which I need to invoke through "MyDelegate". Then I am invoking my method through the delegate. It's simple as that.

Multicasting


Multicasting is, as I mentioned before delegates has the capability to refer more than one method at a time. A multicast delegate maintains a list of functions that will be called when the delegate is invoked. We can add or remove the pointing methods of delegate using "+" and "-" operators. To demonstrate the delegates multicasting, I will just modify the above example as follows.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = null;
            oMyDelegate += new MyDelegate(oMyClass.MyFirstMethod);
            oMyDelegate += new MyDelegate(oMyClass.MySecondMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyFirstMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-First Method", s));
            Console.ReadLine();
        }

        public void MySecondMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-Second Method", s));
            Console.ReadLine();
        }
    }
}
Output :

Multicasting
So that's the basics of delegates in C#. Hope you all got found this post helpful.

Happy Coding.

Regards,
Jaliya

1 comment: