What is Delegate?
A delegate is similar to a function pointer in C or C++. To call the reference method using the delegate object.The delegates typedefinition same as the Function typedefinition.
PROGRAM:(DelegateEg.cs)
using System;
delegate int NumberChanger(int n);
namespace Training
{
class DelegateEg
{
static int num=10;
public static int AddNum(int p)
{
num+=p;
return num;
}
public static int MulNum(int q)
{
num*=q;
return num;
}
public static int getNum()
{
return num;
}
public static void Main(string []arg)
{
NumberChanger nc1=new NumberChanger(AddNum);
NumberChanger nc2=new NumberChanger(MulNum);
nc1(25);
Console.WriteLine("Value of Num:{0}",getNum());
nc2(5);
Console.WriteLine("Value of Num:{0}",getNum());
}
}
}
OUTPUT:
D:\csharp>DelegateEg
Value of Num:35
Value of Num:175
PROGRAM EXPLANATION:
The above program explain how to use the delegates in the c#.The delegate canbe declared outside the class and to create a object to the delegate and call the function using delegate objects.
A delegate is similar to a function pointer in C or C++. To call the reference method using the delegate object.The delegates typedefinition same as the Function typedefinition.
PROGRAM:(DelegateEg.cs)
using System;
delegate int NumberChanger(int n);
namespace Training
{
class DelegateEg
{
static int num=10;
public static int AddNum(int p)
{
num+=p;
return num;
}
public static int MulNum(int q)
{
num*=q;
return num;
}
public static int getNum()
{
return num;
}
public static void Main(string []arg)
{
NumberChanger nc1=new NumberChanger(AddNum);
NumberChanger nc2=new NumberChanger(MulNum);
nc1(25);
Console.WriteLine("Value of Num:{0}",getNum());
nc2(5);
Console.WriteLine("Value of Num:{0}",getNum());
}
}
}
OUTPUT:
D:\csharp>DelegateEg
Value of Num:35
Value of Num:175
PROGRAM EXPLANATION:
The above program explain how to use the delegates in the c#.The delegate canbe declared outside the class and to create a object to the delegate and call the function using delegate objects.