Introduction about delegates and why delegates are came the main purpose of delegates how to useful and what are the advantages and disadvantages and types of delegates all are provided in this article.
Best Tutorial about Delegates
Introduction |
Delegates Introduction
- Delegates are similar like C++ function pointers
- To define we have to use delegate keyword,delegate are reference types.
- delegate can hold the address of a function,using delegate object we can invoke a method without using method name.
Delegates are 2 types
1.Single caste Delegate
It can hold address of a single method
2.Multi Cast delegate:
- It can hold adresses of multiple methods
- using multicast delegate we can ivoke multiple methods with a single call.
Implementation of delegate concept can be divided into following steps
Step1: Defining a class
step2: Defining a method
Step3: Defining a delegate
<Syntax>
<accessmodifier>delegate<returntype><delegatename>(<type><arg1>,<type><arg2>);
step4:creating object for delegateand initializing the method name
<delegatename><delegate objname>=new <delegatename>(<methodname>);
Step5: invokin the method by using delegate object
<delegate ojjname()>;
delegate are called as type function pointers because delegate declaration should follow the mathod declaration which is holding by the delegate object that means method return type and signature should be same for delegate.
Note:
Delegate can hold the address of static methods as well as instance methods.
Example to invoke instance methods by using delegate object(single cast delegate)
namespace singlecastDelegateex1
{
class calculate
{
internal int add(int a,int b)
{
return a+b;
}
}
internal delegate int Mydelegate(int x,int y);
class Program
{
void main()
{
calculate obj=new calculate();
MyDelegate delobj=new MyDelegate(obj.add);
int res=delobj(10,5);
console.WriteLine("addition result is :"+res);
console.ReadLine();
}
}
}
Friends you like my post please share to your friends through Facebook,Twitter,Google+.
0 comments:
Post a Comment