Thursday, 17 December 2015

Delegates Part 1

Delegate(Part 1)


"A delegate is similar to a pointer function in C or C++  that holds reference of a method.It allows to encapsulate reference to a method inside a delegate object .The delegate object can be passed to a code which can call the reference method."
You often read such definitions about delegates ,this is true but incomplete .The real purpose of a Delegate is to communicate .As 'delegate' is a English language word and  the meaning of this word is to represent or communicate between/among communities ,classes etc.
So the delegate are for communication. We use delegate when one class want to communicate with other class. Of course there are several other ways of doing that,but we should adopt the best way to do any thing.

Why we use Delegate?
C# does not allow us passing method reference directly as arguments  to other methods ,rather it provides delegates.

For example you write a Class(of code) .In this Class you have written a method .A second person working in your team or else where needs this method which you have written in your class. You would provide delegate to that person so that he/she can call this method.

Delegates are especially useful in event driven environment such as Graphical User Interface(GUI) in which you want that code execute when user clicks the button.


Note:Delegates are classes that encapsulate set of references to method.

There are two types of delegate

  1. Single Cast Delegate
  2. Multi Cast Delegate 

(See the detail of both in later section)

Single Cast Delegate:A delegate that contains a single method is known as Single Cast delegate. And it is derived from the class Delegate.
Multi Cast Delegate:  A delegate that contains multiple methods are Multi Cast Delegate. 
Both Single Cast Delegate and Multi Cast Delegate belong to Name-space System.

Before using delegates following point must consider:

"The method header (Parameter & return value) of a delegate and the method whose reference will be within a delegate object must have same method header."

Lets proceed to some practical examples

There are following steps involved in using Delegates:
Declaration
Instantiation
Invocation
Example 1: A simple Delegate

using System;

namespace Simple.Delegate
{
    //  Step 1:Declaration
    public delegate void SimpleDelegate();

    class MyClass
    {
        public static void Print()
        {
            Console.WriteLine("Delegate was Printed");
        }

        public static void Main()
        {
            //  Step 2:Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(Print);

            // Step 3: Invocation
            simpleDelegate();
        }
    }
}

In the later section,I will write further examples of Delegates.

No comments:

Post a Comment