Action and Func in C#

Needone App
1 min readDec 26, 2020

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));

Hacking with Unity — Learn how to create your own games Newsletter

Join the newsletter to receive the latest updates in your inbox.

Originally published at https://hackingwithunity.com on December 26, 2020.

--

--