C# Delegates: Func Delegate, Action Delegate and Predicate Delegate

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.


For example, if you click on a Button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed.

There are three steps involved while working with delegates:

  1. Declare a delegate

  2. Set a target method

  3. Invoke a delegate


Important Points:

  • Provides a good way to encapsulate the methods.

  • Delegates are the library class in System namespace.

  • These are the type-safe pointer of any method.

  • Delegates are mainly used in implementing the call-back methods and events.

  • Delegates can be chained together as two or more methods can be called on a single event.

  • It doesn’t care about the class of the object that it references.

  • Delegates can also be used in “anonymous methods” invocation.

  • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.


Syntax:

A delegate can be declared using the delegate keyword followed by a function signature, as shown below.

[access modifier] delegate [return type] [delegate name]([parameters])