Delegates and Events


In this article I am going to explain you what is delegate, what is method group conversion and also a sample code for that.

C# 2.0 added an option that significantly simplifies the syntax that assigns a method to a delegate. This feature is called method group conversion, and it allows you simply to assign the name of a method to a delegate, without the use of new or explicitly invoking the delegate’s constructor.

ex: public delegate int PerformCalculation(int x, int y);


delegate int ope(int a,int b);
class opec
{

public static int add(int a, int b)
{
return a + b;
}
public static int sub(int a, int b)
{
return a - b;
}
public static int mul(int a, int b)
{
return a * b;
}
public static void Main(String[] arg)
{
ope del = new ope(add);
int a = del(10, 20);
del = new ope(sub);
int b = del(10, 20);
del = new ope(mul);
int c = del(10, 20);
Console.WriteLine("values are " + a + " " + b + " " + c);

}
}


Normally functions we called in loops by object of the class. Each time function stack will creates and execute that function so each time memory will allocates for this execution. Memory will be wasting here, so to resolve this problem Delegate can be used.

Delegate is a function pointer it creates function stack and executes the functions on a same memory location (number of times you called also).
so no separate memory allocation is required each and every time to call a same function.

Delegates' takes function as an argument.


Comments

Author: Somasekar N29 Mar 2012 Member Level: Gold   Points : 0

Good one chidam keep posting...

Author: chidambaram29 Mar 2012 Member Level: Gold   Points : 0

Thank you soma....cograts for silver medal



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: