DEV Community

Cover image for Delegate, Func and Action in C#
Mo
Mo

Posted on

Delegate, Func and Action in C#

Hi there๐Ÿ‘‹
welcome to my blog where I share my passion for coding in C#. Today, I want to talk about delegate, Func and Action. Sounds exciting, right? ๐Ÿ˜‰

Delegates ๐Ÿš€

Delegate is a type that represents a method with a specific signature. It allows you to pass a method as a parameter to another method, or store it in a variable. Delegate is very useful when you want to create callbacks, events, or asynchronous operations.

Here is a simple example of a delegate declaration:

public delegate void MyDelegate(string message);

// Method that matches the delegate signature
public static void MyMethod(string message)
{
    Console.WriteLine(message);
}

// Using the delegate
MyDelegate myDelegate = new MyDelegate(MyMethod);
myDelegate("Hello, Delegate!");

Enter fullscreen mode Exit fullscreen mode

In the example above, MyDelegate is declared with a signature that takes a string parameter. The MyMethod method matches this signature, and an instance of the delegate is created and used to call the method.

But delegate has some drawbacks. It is verbose and requires you to define a delegate type for each method signature.

delegate is verbose

That's why C# introduced two generic delegate types: Func and Action.

Func and Action ๐Ÿงฉ

Func and Action are predefined delegate types that can take any number of parameters and return a value or not. Func is used when you want to return a value, and Action is used when you don't. For example:

Func:

Func<int, int, int> add = (a, b) => a + b;
int result = add(5, 7);
Enter fullscreen mode Exit fullscreen mode

Action:

Action<string> printMessage = message => Console.WriteLine(message);
printMessage("Hello, Action!");
Enter fullscreen mode Exit fullscreen mode

Using Func and Action makes your code more concise and readable. You can use them with LINQ, lambda expressions, or any method that expects a delegate. They are also compatible with the built-in delegate types like EventHandler or Predicate.

Why Func and Action? ๐Ÿ”Ž

  • Conciseness: Func and Action provide a more concise syntax for defining delegates, especially when working with methods that take parameters or return values.
  • Readability: The use of generic types in Func and Action makes code more readable, as you don't need to explicitly declare delegate types.
  • Compatibility: Func and Action are compatible with LINQ expressions and other functional programming constructs, making them well-suited for modern C# development.

Reading

I hope you enjoyed this post and learned something new about delegate, fun and action in C#. If you have any questions or feedback, feel free to leave a comment below.
Happy coding!๐ŸŒŸ

Top comments (0)