Delegates : It is Similar to C++ function pointers,
with in delegate Objects we can store the Methods
syntax for creating delegate: <access modifier> Delegtae <return type> <delegtaeName>(arguments);
syntax for creating Object for Delegate :<DelegateName? <objName> = new <DelegateName>(address of Method);
Types of Delegates:
1. single Caste Delegate (We can Store only single Method)
2. Multi Caste Delegate (We can Store more than one Method)
Example on Single Caste Delegate:
using System;
namespace SingleCaste
{
public class class1
{
public int add(int a,int b)
{
return a+b;
}
}
//create Delegate
public delegate int mydelegate(int a,int b);
class program
{
static void Main (strings[] args)
{
class1 c1 = new class1();
mydelegate md = new mydelegate(c1.add)'
console.writeline("Add;"+md(4,5));
console.readline();
}
}
}
example prog ram on MultiCaste Delegate:
using System;
namespace multicaste
{
public class class1
{
public void add(int a,int b)
{
console.writeline("add:"+(a+b));
}
public void sub(int a,int b)
{
console.writeline("sub:"+(a-b));
}
public void mul(int a,int b)
{
console.writeline("mul:"+(a*b));
}
}
//create Delegate
public delegate void MultiDel(int a,int b);
class program
{
static Void Main(String[] args)
{
class1 c1 = new class1();
MultiDel md = new MultiDel(c1.add);
md += c1.mul;
md += c1.sub; //+= is used to add method to delegate
md(1,2);
md -= c1.mul; //-= is used to remove method from delegate
md(4,5);
console.readline()
}
}
}
Saranya Boopathi, if this helps please login to Mark As Answer. | Alert Moderator