C# Delegate
In C#, a Delegate is a type-safe function pointer that allows a method to be passed as a parameter to another method.
A Delegate in C# is similar to a function pointer in C or C++.Delegate is a reference type variable that holds a reference to a method; the reference can be changed at runtime.
Delegates are very common in C#, used for event handling, callback functions, LINQ operations, and more.
All delegates (Delegate) derive from System.Delegate class.
Declaring a Delegate
A delegate is a reference type that defines a method signature and can be used to store methods that match that signature. Through a delegate, you can call methods in other classes.
A delegate declaration determines the methods that can be referenced by the delegate. A delegate can point to a method that has the same signature as itself.
The syntax for declaring a delegate is as follows:
public delegate
Format description:
public delegate 返回类型 委托名(参数类型 参数名, ...);
For example, in the following code we define a delegate that accepts two integers and returns an integer:
public delegate int MathOperation(int x, int y);
The delegate in the following example can be used to reference any method with a single string parameter that returns a int variable of type.
public delegate int MyDelegate (string s);
Instantiating a Delegate
Once a delegate type is declared, the delegate object must be created using the new keyword and must be associated with a specific method. When creating a delegate, the argument passed to the new statement is written like a method call, but without arguments. For example:
public
delegate
void
printString
(
string
s
)
;
...
printString
ps1
=
new
printString
(
WriteToScreen
)
;
printString ps2
=
new
printString
(
WriteToFile
)
;
The following example demonstrates the declaration, instantiation, and use of a delegate that can be used to reference a method with an integer parameter and return an integer value.
Example
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 a delegate instance
NumberChanger nc1
=
new
NumberChanger
(
AddNum
)
;
NumberChanger nc2
=
new
NumberChanger
(
MultNum
)
;
// Call the method using the delegate object
nc1
(
25
)
;
Console
.
WriteLine
(
"Value of Num: {0}"
, getNum
(
)
)
;
nc2
(
5
)
;
Console
.
WriteLine
(
"Value of Num: {0}"
, getNum
(
)
)
;
Console
.
ReadKey
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175
Multicasting of a Delegate
Delegate objects can be combined using the + operator.
A combined delegate calls both delegates it combines; only delegates of the same type can be combined.
- The - operator can be used to remove a component delegate from a combined delegate.
Using this useful feature of delegates, you can create an invocation list of methods to be called when the delegate is invoked. This is called multicasting, also known as group multicasting.
The following program demonstrates multicasting of delegates:
Example
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 a delegate instance
NumberChanger nc
;
NumberChanger nc1
=
new
NumberChanger
(
AddNum
)
;
NumberChanger nc2
=
new
NumberChanger
(
MultNum
)
;
nc
=
nc1
;
nc
+=
nc2
;
// Invoke multicasting
nc
(
5
)
;
Console
.
WriteLine
(
"Value of Num: {0}"
, getNum
(
)
)
;
Console
.
ReadKey
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
Value of Num: 75
Uses of a Delegate
The following example demonstrates the use of a delegate. The delegate printString can be used to reference a method that takes a string as input and returns nothing.
We use this delegate to call two methods: the first prints the string to the console, and the second prints the string to a file:
Example
using
System
;
using
System.IO
;
namespace
DelegateAppl
{
class
PrintString
{
static
FileStream fs
;
static
StreamWriter sw
;
// Delegate declaration
public
delegate
void
printString
(
string
s
)
;
// This method prints to the console
public
static
void
WriteToScreen
(
string
str
)
{
Console
.
WriteLine
(
"The String is: {0}"
, str
)
;
}
// This method prints to a file
public
static
void
WriteToFile
(
string
s
)
{
fs
=
new
FileStream
(
"c:\message.txt"
, FileMode
.
Append
, FileAccess
.
Write
)
;
sw
=
new
StreamWriter
(
fs
)
;
sw
.
WriteLine
(
s
)
;
sw
.
Flush
(
)
;
sw
.
Close
(
)
;
fs
.
Close
(
)
;
}
// This method takes a delegate as a parameter and uses it to call a method
public
static
void
sendString
(
printString ps
)
{
ps
(
"Hello World"
)
;
}
static
void
Main
(
string
[
]
args
)
{
printString ps1
=
new
printString
(
WriteToScreen
)
;
printString ps2
=
new
printString
(
WriteToFile
)
;
sendString
(
ps1
)
;
sendString
(
ps2
)
;
Console
.
ReadKey
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
The String is: Hello World
Removing a Delegate
If you no longer need a method, you can remove it from the delegate chain using the -= operator.
Example
public
class
Program
{
public
delegate
void
PrintMessage
(
string
message
)
;
public
static
void
PrintUpperCase
(
string
message
)
{
Console
.
WriteLine
(
message
.
ToUpper
(
)
)
;
}
public
static
void
PrintLowerCase
(
string
message
)
{
Console
.
WriteLine
(
message
.
ToLower
(
)
)
;
}
public
static
void
Main
(
)
{
PrintMessage print
=
PrintUpperCase
;
+=
PrintLowerCase
;
// Remove the PrintLowerCase method
-=
PrintLowerCase
;
// Invoke the delegate (only PrintUpperCase will be called)
(
"Hello, C#"
)
;
// Output: HELLO, C#
}
}
Delegates and Events
Delegates are often used together with events. An event is a special type of delegate used for the publish-subscribe mechanism.
In C#, an event is essentially a type that encapsulates a delegate; it is used to respond to certain actions in a program.
Example
public
class
Button
{
// Define an event
public
event
EventHandler Click
;
// Method that raises the event
public
void
OnClick
(
)
{
if
(
Click
!=
null
)
{
Click
(
this
, EventArgs
.
Empty
)
;
// Invoke the event
}
}
}
public
class
Program
{
public
static
void
Main
(
)
{
Button button
=
new
Button
(
)
;
// Subscribe to the event
button
.
Click
+=
Button_Click
;
// Raise the event
button
.
OnClick
(
)
;
// Output "Button clicked!"
}
private
static
void
Button_Click
(
object
sender, EventArgs e
)
{
Console
.
WriteLine
(
"Button clicked!"
)
;
}
}
Types of Delegates
C# provides several common delegate types:
1、Action
Action: represents a method that does not return a value. It can accept up to 16 parameters.
Action printMessage = Console.WriteLine;
printMessage("Hello");
2、Func
Func: represents a method that has a return value. It accepts up to 16 parameters; the first parameters are input parameters and the last parameter is the return type.
Func add = (x, y) => x + y;
Console.WriteLine(add(3, 4)); // 输出 7
3、Predicate
Predicate: represents a method that returns a bool value, typically used for conditional checks.
Predicate isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // 输出 True
Notes on Delegates
**Type safety:** Delegates are type-safe, which means only methods with matching signatures can be assigned to a delegate.
Anonymous methods and lambda expressions: You can use anonymous methods or lambda expressions to create delegate instances, simplifying your code.
Func add = (x, y) => x + y;
Console.WriteLine(add(5, 3)); // 输出 8
Asynchronous invocation: Delegates can be used with the BeginInvoke and EndInvoke methods for asynchronous calls.
Delegates are a very powerful and flexible feature in C#, enabling event-driven programming, callback mechanisms, and functional programming styles. They not only provide code reusability but also improve program modularity. Understanding and mastering the use of delegates is very important for C# programming.