Variants one & two are examples of actions rather than functions. In C# a function (or Func<T>
) is something callable that returns a value (i.e. T
in the previous case), whereas an action (or Action
) is something callable that doesn't return a value. An Action
is analogous of a void
returning method.
Functions are handy for injecting some of your consumer code into the execution of another function.
For example, you have a list of users & you want a list of all the user's full names instead. You don't want to have to write a loop just to convert a User
to a string
, you just want to express the transformation & have it done for you, so you use a function that does the loop for you (i.e. IEnumerable<T>.Select
).
All you want to do is define how a User
is transformed into a string
, which you can do by passing a Func<User, string>
inline (where the User
represents the input of the function, and the last parameter string
refers to the output of the function):
IEnumerable<User> users = new User[] {
new User { FirstName = "John", LastName = "Doe" }
};
IEnumerable<string> fullNames = users.Select(user => $"{user.FirstName} {user.LastName}");
class User {
public string FirstName { get; set; }
public string LastName { get; set; }
}
The obvious benefit of this is that it's more expressive, because you're eliminating boilerplate & potential mistakes. You're soaking that up into Select
and all you're just describing to it how you want it to transform the data (when it ultimately yields the elements).