==>>A Delegate is a special type function means it can point to those function which are having identical signature with delegate.
you can also call delegate as a interface of methods as this acts same as interface in c# but that implemented for classes and this is implemented for methods..
* Step to create a delegate:
1 . Declaration
2. Instantiation
3. Invocation
* Why we need Delegate.......
- We can call many of method by single delegate no need of writ many of function.
- We set up event based system easily.
- We can calling many method that in different but having same signature.
- We can passing in parameter field a function.
- we can use select method.
You take a new console application in visual studio and write the sample code in cs file:---
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
public delegate string MyDelegate();//Declaration
public class TestDelegat
{
public string TestMethod()
{
return "This is Delegate Sample Program in C#.";
}
}
class Program
{
static void Main(string[] args)
{
TestDelegat TD = new TestDelegat();
MyDelegate MDel = new MyDelegate(TD.TestMethod);//Insatantiation
Console.Write("Output: " + MDel());//Invocation
}
}
}
first we define a delegate name with its signature,in this case its return type is string and no arguments. then we create instance of delegate which is MyDelegate now this can point to (reference to) all those function which having same signature as in our case function is TestMethod() and at the last we invoke this and receive this in message.
The main advantage of delegate is multi cast ...
*For use multi cast we need write this code
In The Class..
public void TestMethodMulticast()
{
console.write("Multicast");
}
and in the Static Void Main
MyDelegate TD= null;
TD+= new MyDelegate (TD.TestMethod);
TD+= new MyDelegate (TD.TestMethodMulticast);
Hope this post will help you for find your solution
Happy Coding