Types of Delegates in C#

Introduction

Delegates are types in C# that represent references to methods. Methods can be treated as first-class citizens thanks to the language's robust delegate feature, which also enables you to retain references to methods, send methods as parameters to other methods, and generate dynamic method invocations. The implementation of callbacks, event handling, and other situations where it is necessary to separate the source of an event from its handlers all benefit from the use of delegates. A thorough description of delegates in C# is provided below:

Delegate Declaration

To create a delegate, use the delegate keyword and a signature that corresponds to the method(s) it can refer to. The method's return type and parameter types are specified in the signature. A delegate that can refer to methods returning a string with an integer parameter, for instance, is declared as follows:

delegate string MyDelegate(int value);

Delegating Instantiation

Delegates can be created by giving a reference to a method with a matching signature or by instantiating a delegate. To create a delegate, you can alternatively use an anonymous method or lambda expression. For instance:

MyDelegate delegateInstance = SomeMethod;
// or
MyDelegate delegateInstance = x => (x * 2).ToString();

Invoking Delegates

You can call a delegate just like a method, passing arguments in accordance with the signature. The delegate is invoked by calling the method it references, passing the method's parameters, and returning the outcome (if any).

string result = delegateInstance(5); // Invokes the referenced method with the argument 5

Multicast Delegates

In C#, delegates have the ability to be multicast, which allows them to reference many methods. Multiple methods added to a delegate are called in the order in which they were added. The delegate can have methods added to it using the += operator and removed using the -= operator.

MyDelegate delegate1 = Method1;
MyDelegate delegate2 = Method2;
MyDelegate multicastDelegate = delegate1 + delegate2;
// You can now invoke multicastDelegate to call both Method1 and Method2.

Use Cases

In C#, delegates are frequently used for a variety of tasks.

  • Event Handlers: Delegates are the cornerstone of C# events in terms of handling them. They make it possible to separate event sources from event handlers.
  • Callbacks: Delegates are used to create mechanisms for callbacks, in which one method calls another one after it has finished.
  • Extensibility: Delegates' extensibility makes it possible to build architectures that are expandable and pluggable since new methods can be added to existing delegates without changing the existing code.
  • Invocation of Dynamic Method: Delegates are used to call methods dynamically at runtime based on input from users or applications.
  • Built-in Delegate Types: The built-in delegate types that C# offers, including Action and Func, make it simpler to work with delegates without having to define unique delegate types.

'Action' Methods without a return value are represented by action delegates.

Action<string> actionDelegate = DisplayMessage;
actionDelegate("Hello, delegates!");

'Func' Func delegates stand in for methods that provide results.

Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 3);

Predicate Delegate A particular delegate called a "predicate" is used for methods that return boolean values, which are frequently used for collection filtering.

Predicate<int> isEven = x => x % 2 == 0;
bool result = isEven(6); // true

Conclusion

Delegates in C# are a powerful mechanism that allows you to work with methods as if they were first-class objects, enabling dynamic method invocation, creating modular and extensible code, and providing the foundation for event-driven programming. They are a fundamental concept in C# and essential for various advanced programming scenarios.

Please feel free to drop a comment if you have any queries related to this post.

Thanks


Similar Articles