You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Action and Func in C#

Ben Liu
Ben Liu

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

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp