Delegates

Nadeemshaik
Posted by in C# category on for Beginner level | Points: 250 | Views : 3755 red flag

Types of Delegates with example program


Delegates


It is Similar to C++ function pointers, with in delegate Objects we can store the Methods. We can access the methods with in the Main() by using Delegate Objects without using Method name. Delegate is not a member with in the Class 


syntax for creating delegate: <access modifier> Delegtae <return type> <delegtaeName>(arguments); 
syntax for creating Object for Deleg ate :<DelegateName? <objName> = new <DelegateName>(address of Method); 


Types of Delegates: 

1. Single Cast Delegate (We can Store only single Method) 
2. Multi Cast Delegate (We can Store more than one Method) 
Example on SingleCast Delegate:

using System; 

namespace SingleCast 
{ 
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 program on MultiCast Delegate:

using System; 

namespace multicast 
{ 
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() 
} 
} 
}



Page copy protected against web site content infringement by Copyscape

About the Author

Nadeemshaik
Full Name: Nadeem Shaik
Member Level: Starter
Member Status: Member
Member Since: 5/1/2013 6:06:27 AM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Saratvaddilli on: 7/4/2013 | Points: 25
nice article

Login to post response

Comment using Facebook(Author doesn't get notification)