Wednesday, March 10, 2010

What are delegates??

Hello Guys,
This is the common interview question that every one asks to an experienced employee. The questions follow like this.
What are delegates? What is the practical approach to use delegate?
What are multicast delegates??
In my blog I will explain what they are.

Delegate:

(MSDN def)

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value,

An Image worth thousand words. In the image I delcared a delegate with the name perform , takes a input integer paramter, and produces output int parameter.

So any methods with the input int parameter and output int paramter are ready to go to the delegate place.

In the class a, instantiating delegate and assigning it to method(square or Cube). They both are ready to act in place of delegate since they have same signature.

Now

Op(2) means that Sqaure(2)

Op1(2) means Cube(2)

Thats the power of Delegate, it acts like any other methods.

Multicast Delegates:

If a delegate points to more than one function at a time then it is called multicast delegate.

Think we have 4 delegate instances a , b ,c , d

ex: Perform a, b, c, d;
a= Square;
b = Cube;
c = a + b;
d = c - a;

Resposnse.Write(c(2).ToString());
Response.Write(d(2).ToString());

The outputs will be 8

So guys are you ready to face the interview. So here are the definitions:

Delegate : A delegate is a function pointer , where the functions will have the same signature as of delegate. input and output parameters are same.

Multicast delegate: If a delegate calling more than one function, then it is calling Multicast delegate.

All the best.

No comments:

Post a Comment