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

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.

--

--

--

needone.app

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Unity — Health powerup

Bankruptcy Law

bankruptcy law

The Top 15 Websites to Learn To Code

Day 46,47/100daysofK8s

Product Support at a RegTech Startup from scratch

TzFlow — A Useful Tool for Displaying On-Chain Data

Understanding AWS Control Tower

AI engineering: making AI real

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Needone App

Needone App

needone.app

More from Medium

What are Middlewares and How They are Used in .NET

Var datatype in C#

How to update .NET core 5.0 to 6.0

NET5 Exception Handling Made Easy