I was wondering if someone could explain what Func<int, string>
is and how it is used with some clear examples.
We could define a function where the domain X is again the set of people but the codomain is a set of numbers. For example, let the codomain Y be the set of whole numbers and define the function c so that for any person x, the function output c(x) is the number of children of the person x.
1 : the action for which a person or thing is designed or used : purpose What function does this tool serve? 2 : a large important ceremony or social affair. 3 : a mathematical relationship that assigns exactly one element of one set to each element of the same or another set.
The types of functions can be broadly classified into four types. Based on Element: One to one Function, many to one function, onto function, one to one and onto function, into function.
Types of FunctionsOne – one function (Injective function) Many – one function. Onto – function (Surjective Function) Into – function.
Are you familiar with delegates in general? I have a page about delegates and events which may help if not, although it's more geared towards explaining the differences between the two.
Func<T, TResult>
is just a generic delegate - work out what it means in any particular situation by replacing the type parameters (T
and TResult
) with the corresponding type arguments (int
and string
) in the declaration. I've also renamed it to avoid confusion:
string ExpandedFunc(int x)
In other words, Func<int, string>
is a delegate which represents a function taking an int
argument and returning a string
.
Func<T, TResult>
is often used in LINQ, both for projections and predicates (in the latter case, TResult
is always bool
). For example, you could use a Func<int, string>
to project a sequence of integers into a sequence of strings. Lambda expressions are usually used in LINQ to create the relevant delegates:
Func<int, string> projection = x => "Value=" + x; int[] values = { 3, 7, 10 }; var strings = values.Select(projection); foreach (string s in strings) { Console.WriteLine(s); }
Result:
Value=3 Value=7 Value=10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With