DELEGATE in C#
A delegate is special type of object that contains that
detail of a method rather than data. A delegate can be used to hold the reference
of a method of any class. It carries three important pieces of information- he
name of the method on which it makes call, the argument (if any) f this method,
and the return value (if any) of this method.
“Basically it is similar like the old "C" as function pointer.”
“Basically it is similar like the old "C" as function pointer.”
Following
are the four steps to create and use a delegate in your program.
- Declaring a delegate.
- Defining delegate methods.
- Creating delegate objects.
- Invoking delegate objects.
Declaring a delegate
Although the syntax of declaring a delegate is similar to that of declaring a method (without method body) ,the delegate actually represent the class type.
A delegate can be declared using following syntax:-
access modifier delegate return_type delegate_name (parameter list);
EXAMPLE:-
Public delegate void Result (int x , int y);
Defining delegate Method
A delegate method is any method whose signature (number and type of parameter and return type) matches the delegate signature exactly.
EXAMPLE:-
1. Public static void add(int a, int ,b)
{
console.writeLine(“sum = {0}”,a+b);
}
2. Public void sub(int a, int ,b)
{
console.writeLine(“Subtract = {0}”,a-b);
}
A delegate method is any method whose signature (number and type of parameter and return type) matches the delegate signature exactly.
EXAMPLE:-
1. Public static void add(int a, int ,b)
{
console.writeLine(“sum = {0}”,a+b);
}
2. Public void sub(int a, int ,b)
{
console.writeLine(“Subtract = {0}”,a-b);
}
Creating Dlegate object
Syntax:-
Delegate name object name=new delegate name (expression);
EXAMPLE:-
MyClass my = new MyClass(); //class object
Result add = new Calculate(my.add);
Result sub = new Calculate(my.sub);
Syntax:-
Delegate name object name=new delegate name (expression);
EXAMPLE:-
MyClass my = new MyClass(); //class object
Result add = new Calculate(my.add);
Result sub = new Calculate(my.sub);
Invoking delegate object
The following code snippet show the syntax to declare a delegate object:-
Delegate object (argument list);
EXAMPLE:-
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));
The following code snippet show the syntax to declare a delegate object:-
Delegate object (argument list);
EXAMPLE:-
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));
<<<<<<<<<<<<<<<<<<<<<
0 comments