This is the most
powerful and exciting new feature of c#
or c sharp. This concept , the core of object oriented programming , allows you
to worry more about the flow of the system at lowest level, without worrying
about the specifics of individual tasks that will be handled.
What does delegate
means? In UK,USA ,people elect
their delegates to represent their
legislature or council. These Delegates represent the entire nation or state
because it is impossible if the entire populations were to present to represent
countries. In short ,you can say delegates is like as function pointer in c or c++.
What is Function pointer?
Function pointer is pointer .i.e variable , which point to
the address to the function.
In other word we define delegates “ it allows us to reference of method.”
Types Of Delegates:
There are two types of delegates:-
1.)Single cast delegates
2.)Multiple cast delegates
Syntax of Delegate:
1.)Single cast delegates:
public Delegate
<return
type>
<delegate_name>(parameters)
2.)Multiple cast delegates:
public Delegate void <delegate_name >(parameters)
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate
{
public delegate int Delg(int x,int y);
public class Math
{
public static int Add(int x,int y)
{
return x + y;
}
public static int Mul(int x,int y)
{
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
Delg del = new Delg(Math.Add
);
int add = del(7,7);
Console.WriteLine(add);
Delg del1 = new Delg(Math .Mul );
int mul1 = del1(5,6);
Console.WriteLine(mul1);
Console.ReadLine();
}
}
}
Advantages of Delegates:
Dynamic binding can be done by using delegate because we can
call more than one method at a time dynamically by calling the delegate in
which method is defined.
Static delegate is used for delegate without creating a local delegate instant. Just pass
in the static delegate of class.
Disadvantage of delegate:
The problem with static delegate that it must be instantiated
whether they are in use or not.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.