Answer: Delegates in C# programming is a type safe function pointer that points to a function by having a reference to that function.
To create a delegate we use “delegate” keyword. For example
public delegate int FunctionPointer(int x,int y);
Now, “FunctionPointer” is called a delegate that accept two int values as parameters and returns int value, that will be used to point any method which have same specification (method signature, return type).
As another example, let’s create a delegate that receives a string and returns nothing.
public delegate void FunctionPointerString_delegate(string str);
Now, this delegate will be used to point any method that have same specification i.e . void StudentName( string name), void StudentAddress(string Adrr) etc.
To point a function, just we need to create an object of a delegate and assign a function name.
Let’s say we have a function “int sum(int a, int b)” with the same return type and signature as we have in delegate FunctionPointer.
FunctionPointer fPointer = Sum;
Now we can call a function using delegate object like below
Int result = fPointer(5,5);
Delegates program example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateUsage
{
public delegate int FunctionPointer(int x,int y);
class Test
{
static void Main(string[] args)
{
FunctionPointer fPointer = sum;//assign a function name
int result = fPointer(5,5); // call a function using delegate object.
Console.WriteLine(result);
}
public static int sum(int a, int b)
{
return a + b;
}
}
}
Note that same delegate object can be used to call any functions that is compatible to delegate (same return type and parameters).
Note that the prototype of delegate and referenced methods must be same that’s why it is called as ‘type safe function pointer’ i.e.
Delegate : public delegate int FunctionPointer(int x,int y);
Method : public static int sum(int a, int b);