Delegates

 This is the new concept introduced in C#.
 Def: A delegate is the reference to the method.
 Using the delegate, you can call the method.
 This is used in “GUI Events” and “Multi-Threading” concept in future.

Implementation Syntax:

1. Define the Method:
accessmodifier returntype methodname(arguments)
{
//some code
}

2. Declare the delegate (as a data member):
delegate returntype delegatename(arguments);

3. Create instance of the delegate:
delegatename delegateinstancename = new delegatename(methodname);

4. Access the properties of the delegate:
 delegateinstancename.Target
//gets the class name that contains the target method
 delegateinstancename.Method
//gets the signature of the target method
5. Invoke / call the target method:
delegateinstancename.Invoke();
(or)
delegateinstancename.Invoke(arguments);

Delegates

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatesDemo
{
class Sample
{
public int GetSum(int a, int b, int c)
{
return (a + b + c);
}
}
class Program
{
delegate int SampleDelegate(int a, int b, int c);
static void Main(string[] args)
{
Sample s = new Sample();
SampleDelegate sd = new SampleDelegate(s.GetSum);
Console.WriteLine("Target Method: " + sd.Target);
Console.WriteLine("Target Method Signature: " + sd.Method);
Console.WriteLine("Sum is: " + sd.Invoke(10, 20, 30)); //calls the method
Console.Read();
}
}
}
deligate