+ 5
How does the func keyword in c# work?
Please provide a use case of the func keyword in c# and break it down into concise explanations for each piece. Thanks.
3 Answers
+ 5
I see now that Func is a delegate type that encapsulates a method. Being declared with, first, the parameter types of the method and, lastly, the return type.
Explanation, using the following example:
Func<string, int> ParseStringToInt = n => Convert.ToInt32(n);
The first bit: Func<string, int>
Declaring a Func delegate type, taking a string value as parameter and
returning value of type int
The second bit: ParseStringToInt =
The delegate identifier and assignment operator, assigning the following
defined lambda expression
The third bit: n => Convert.ToInt32(n);
The lambda expression, encapsulated method, being assigned to the
delegate
If this explanation is wrong or can be improved upon (I'm sure it can be), please comment.
+ 3
The Func delegate type always returns something, so it can't have a return type of void, but you can use the Action delegate type, which executes an action and returns nothing. See the example here: https://code.sololearn.com/chijxkY7V14U/?ref=app
+ 2
I have the same question, but can I use âvoidâ in the second type?