Saturday, 19 May 2012

Delegates in C#

Delegates
Delegates are reference types in C# , which holds address of a method(s).
Single cast delegate which holds address of single method.
Multicast cast delegate which holds address of multiple methods. return type is last method in the invocation list.

By default all delegates are derived from System.Delegate.

Delegate can be instance type/static.  If delegate is instance type,System.Delegate Target property holds address of the methods ,if it is static System.Delegate  Target  property  is null.

Delegate Example
delegate bool checkEven(int x); //delegate declaration: delegates references a method return bool  and takes int as input param.


namespace ConsoleApplication
{
    public class Program1
    {
        delegate bool checkEven(int x);
        public static void Main()
        {
            checkEven even = isEven; //instantiate delegate & assign method address to delegate
            //calling delegate, is nothing but calling method indirectly;
            bool b = even(10);
            Console.WriteLine(b);

             b = even(9);
            Console.WriteLine(b);

//delegate target
Console.WriteLine(even.Target); //null because delegate pointing/referencing to static method
        }
        static bool isEven(int x)
        {
               return (((x%2)==0)?true:false);
          }
    }
}

Output:
True
False

Note: delegates can be part of namespace/within class member, but not within a function body.


Delegates Versus Interfaces
public interface Icalculator
{
  int Add(int x,int y);
}

public class CalService:Icalculator
{
        int  Add(int x,int y)
         {
                  return x+y;
         }
}

delegate int myDel(int x,int y);
public static void Main()
{
         CalService cService = new CalService();
         Console.WriteLine("With Interface the value is {0}",cService.Add(10,20));

          //with delegates
            myDel del= new myDel(Addnum);
   COnsole.WriteLine("With Delegates value is={0}",del(10,20));
}

static int Addnum(int x,int y)
{
 return x+y;
}

Output
Note:Whatever u can do with delegates, samething can be done with interfaces, but every class must implement that interface. 2)This will only work with single method(i.e multicast environment it will not work).


Contravariance & Covariance in delegates.
Contravariance 


delegate void StringDel(String str);

            StringDel sdel = new StringDel(Print);
            sdel("Hello");
        static void Print(object o)
        {
            Console.WriteLine(o); //in this case object o up-casted to string type.
        }

Covariance 
     delegate object covardemo();
        covardemo cd= new covardemo(getString);
        Console.WriteLine(cd());
static string getString(){return "Hello";}
In this case delegate expects return type as object, but gets string this is called covariance.