In this article, we will explore the different ways to combine delegates in C#.
What is Delegate?
A delegate is a type of variable that may contain a reference to a method or an object that refers to that method. Delegates in C# are similar to a function pointer in C/C++.
As an example, the program will call a specific method whenever you click on the button on the form (Windows Form application). In simple terms, it is a type that holds references to methods with specific argument lists and returns types and, when called, executes the method in a program.
How to Combine Delegates in C#?
You can combine delegates in C# using:
1: Using + and += Operators
You can combine delegates in C# using the + and += operators combine.
Example
Here is the C# program’s source code for combining two delegates.
delegate void MyDelegate(string message);
class Program {
static void Main(string[] args) {
MyDelegate delegate1 = message => Console.WriteLine("Delegate 1: " + message);
MyDelegate delegate2 = message => Console.WriteLine("Delegate 2: " + message);
// Combine the delegates using the + operator
MyDelegate combinedDelegate = delegate1 + delegate2;
// Invoke the combined delegate
combinedDelegate("Hello, LinuxHint!");
}
}
2: Using Delegate.Combine() Method
You can also use the Delegate.Combine method to combine delegates in C# and the code for such a case is given below:
delegate void MyDelegate(string message);
class Program {
static void Main(string[] args) {
MyDelegate delegate1 = message => Console.WriteLine("Delegate 1: " + message);
MyDelegate delegate2 = message => Console.WriteLine("Delegate 2: " + message);
// Combine the delegates using the Delegate.Combine method
MyDelegate combinedDelegate = (MyDelegate)Delegate.Combine(delegate1, delegate2);
// Invoke the combined delegate
combinedDelegate("Hello, LinuxHint!");
}
}
Conclusion
In C#, a delegate is a specific type of variable that can refer to a method and is an object that holds a reference to that method. In C#, there are two ways to combine delegates: using the + and += operators, and Delegate.Combine() method. Understanding all these methods will help choose the one according to your needs.