Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to declare and instantiate Delegates in C#?
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime, making delegates powerful tools for implementing callback methods and event handling.
Syntax
Following is the syntax for declaring delegates −
delegate <return type> <delegate-name> <parameter list>
Following is the syntax for instantiating delegates −
<delegate-name> delegateInstance = new <delegate-name>(MethodName);
How Delegate Instantiation Works
Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is the method name without parentheses or arguments.
public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile);
Example
The following example demonstrates how to declare and instantiate delegates in C# −
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
}
}
}
The output of the above code is −
Value of Num: 35 Value of Num: 175
Modern Delegate Instantiation
C# provides simplified syntax for delegate instantiation without explicitly using the new keyword −
using System;
delegate void SimpleDelegate(string message);
class Program {
static void PrintMessage(string msg) {
Console.WriteLine("Message: " + msg);
}
static void Main() {
// Traditional way
SimpleDelegate del1 = new SimpleDelegate(PrintMessage);
// Simplified way (C# 2.0+)
SimpleDelegate del2 = PrintMessage;
// Both work the same way
del1("Hello from del1");
del2("Hello from del2");
}
}
The output of the above code is −
Message: Hello from del1 Message: Hello from del2
Conclusion
Delegates in C# are declared using the delegate keyword followed by a return type and parameter list. They are instantiated using the new keyword or simplified syntax, and can hold references to methods with matching signatures. Delegates provide a flexible way to implement callback mechanisms and event handling in C# applications.
