+ 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.

18th Jul 2017, 4:25 AM
Shane Overby
Shane Overby - avatar
3 Respostas
+ 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.
19th Jul 2017, 1:58 PM
Shane Overby
Shane Overby - avatar
+ 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
7th Apr 2019, 6:28 PM
Shane Overby
Shane Overby - avatar
+ 2
I have the same question, but can I use “void” in the second type?
7th Apr 2019, 4:28 PM
Tomáš Wróbel
Tomáš Wróbel - avatar