Action and Func in C#

· 1 min read
Action and Func in C#

Actions and func are another ways to create delegates.

Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value.

Func is a delegate that points to a method that accepts one or more arguments and returns a value.

  • Action and Func can be used with delegates
  • Action and Func can be used as method parameters

Example of Action

Action doesn't return any value.

// action with generic type
Action<Book> printBookTitle = delegate(Book book)
{
    Console.WriteLine(book.Title);
};
printBookTitle(book);


// action without generic type
Action printLog = delegate {
    Console.WriteLine("log");
};
printLog();

Example of Func

Takes one or more parameters, and return a value which the type is the last parameters.

// Func convert an integer to string
Func<int, string> toString = delegate(int i)
{
    return i.ToString();
};

Console.WriteLine(toString(12));