A delegate is an object that can refer to a method. It means that it can hold a reference to a method. The method can be called through this reference or we can say that a delegate can invoke the method to which it refers. The same delegate can be used to call different methods during the runtime of a program by simply changing the method to which the delegate refers. The main advantage of a delegate is that it invokes the method at run time rather than compile time. Delegate in C# is similar to a function pointer in C/C++.
A delegate type is declared using the keyword delegate. The prototype of a delegate declaration is given below:
delegate ret-type name(parameter-list);
Important Note:A delegate can call only those methods that have same signature and return type as delegate.
Example:
delegate string StrDemo(string str);
This delegate can only call those methods that have string return type and take argument as string.
Example on Delegate.
using System;
// Declare a delegate type.
namespace Test
{
delegate string StrDemo(string str);
class DelegateDemo
{
// Replaces spaces with **.
public string ReplaceSpaces(string s)
{
Console.WriteLine("Replacing spaces with *.");
return s.Replace(' ', '*');
}
// Remove spaces.
public string RemoveSpaces(string s)
{
string temp = "";
int i;
Console.WriteLine("Removing spaces.");
for (i = 0; i < s.Length; i++)
if (s[i] != ' ') temp += s[i];
return temp;
}
}
class MyClass
{
static void Main()
{
DelegateDemo obj = new DelegateDemo();
StrDemo strOp = new StrDemo(obj.ReplaceSpaces);
string str;
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
strOp = new StrDemo(obj.RemoveSpaces);
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
Console.ReadLine();
}
}
}
Output:
Replacing spaces with *.
Resulting string: This*is*a*test.
Removing spaces.
Resulting string: Thisisatest.