|
Delegates in C#
    
‘Delegate’ is one of the powerful features of C#. It is paramount important to understand the delegate concept in order to master the C# language.
Delegate is a type that references a method. Since you can refer to a method as a parameter, delegate is ideal for defining callback methods. Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
The following are the properties of delegates:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to pass methods as parameters.
Delegates can be used to define callback methods.
Example1: The following code demonstrates how a method can be passed through a delegate.
using System;
using System.Collections.Generic;
using System.Text;
delegate void TestDelegate(string message);
namespace DelegateTest
{
class Program
{
static void TestDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
TestDelegate delegate1 = TestDelegateMethod;
TestDelegate delegate2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate1
delegate1("Test");
// Invoke delegate2
delegate2("Delegate");
}
}
}
|
The output of example1 is as follows:
Test
Delegae
Example2: The following example passes two methods with parameters same as delegate through the delegate.
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstDelegate
{
//This delegate can point to any method,
//taking two integers and returning an
//integer.
public delegate int MyDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static int Add(int x, int y)
{
//Console.WriteLine("You are in Add() Method");
return x + y;
}
public static int Multiply(int x, int y)
{
//Console.WriteLine("You are in Multiply() Method");
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MyDelegate
//that points to MyClass.Add().
MyDelegate del1 = new MyDelegate(MyClass.Add);
//Invoke Add() method using the delegate.
int addResult = del1(5, 5);
Console.WriteLine("5 + 5 = {0}\n", addResult);
//Create an Instance of MyDelegate
//that points to MyClass.Multiply().
MyDelegate del2 = new MyDelegate(MyClass.Multiply);
//Invoke Multiply() method using the delegate.
int multiplyResult = del2(5, 5);
Console.WriteLine("5 X 5 = {0}", multiplyResult);
Console.ReadLine();
}
}
}
|
The output of example2 is as follows:
5+ 5 = 10
5 * 5 = 25
|