What Is Delegate with example

Introduction

This article is an attempt to explain a delegate with a simple example. Delegates are similar to function pointers in C++. For simple understanding delegates can be defined as methods that are used to call other method. Only condition to call 

another method from a delegate is that the signature of the calling methods and delegates should match.

Follow these Steps

Delegates should have the same signature as the methods to be called by them. 
i.e. Say that we are calling an addNumbers method which returns an integer by taking (int, int) as input. Then our 

delegate also must have been declared with the same signature. 
Delegate Declaration:
public delegate int simpleDelegate (int a, int b); 

Method:
public int addNumber(int a, int b)

Step For Create And Cal A Delegate

--Create a delegate. A delegate can be created with the delegate keyword, followed by it's return type, then name of the 

delegate with the input patameters.

public delegate int simpleDelegate (int a, int b); 

--Define the methods which are having similar signature as the delegate.

public int mulNumber(int a, int b)
public int addNumber(int a, int b)

--Now we are all set to use the delegates. Just instatiate the class and call the methods using the delegates.

Code Use

using System;
class clsDelegate
{
public delegate int simpleDelegate (int a, int b); 
public int addNumber(int a, int b)
{
return (a+b);
}
public int mulNumber(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate RAPatel = new clsDelegate();
simpleDelegate addDelegate = new simpleDelegate(RAPatel.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(RAPatel.mulNumber);
int addAns = addDelegate(10,12);
int mulAns = mulDelegate(10,10);
Console.WriteLine("Result by calling the addNum method using a delegate: {0}",addAns);
Console.WriteLine("Result by calling the mulNum method using a delegate: {0}",mulAns);
Console.Read();
}
}
Ebook Download
View all
Learn
View all