Simple Delegate Example

Posted by Chvrsri under C# category on | Points: 40 | Views : 6679
First of all we will learn what is a DELEGATE?


A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

In my example i will create a DELEGATE first and then pass a method to that delegate as a parameter. If we encapsulate a single method then it is said to be SingleCastDelegate. If a Delegate can point to more than 1 method at a time then it is said to br MultiCastDelegate. Which iam going to explain now.

Step 1 : Create a class library(Console Application) and name it as DelegateExample

Step 2 : Follow the code and paste it in Program.cs file

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

namespace DelegateExample
class Program
//Intializing a Delegate Here(MULTICAST- Encapsulating more than one method)
public delegate int Calculate(int value1, int value2);

static void Main(string[] args)
SriClass mc = new SriClass();
//This is a MULTICAST Delegate
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);
Console.WriteLine("Addition of 2 Numbers ::" + add(100, 23));
Console.WriteLine("Subtraction of 2 numbers :: " + sub(123, 23));
//Creating a Class with methods inorder to invoke the Delegate Object With Same Signature(ReturnType+Prameters)
class SriClass
public int add(int value1, int value2)
return value1 + value2;
public int sub(int value1, int value2)
return value1 - value2;

The above example is the simple sample to exaplain the concept of Delegate. I created a class with 2 different methods called add() and sub().. Which takes 2 parameters and does the operation of addition and subtraction of 2 numbers.

Hope this code will help the new ones who start Delegates...

Cheers Happy Codeing !!!

Comments or Responses

Posted by: Vinaym on: 5/10/2011 Level:Starter | Status: [Member] | Points: 10
Thank you Srikanth it is very helpful to me
Posted by: Chvlsru on: 4/30/2013 Level:Starter | Status: [Member] | Points: 10
Very helpful to the beginners.....

Login to post response