Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of Func

Tags:

c#

.net

func

I was wondering if someone could explain what Func<int, string> is and how it is used with some clear examples.

like image 816
zSynopsis Avatar asked May 18 '09 16:05

zSynopsis


People also ask

What is a function explain with example?

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.

What is the main meaning of function?

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.

What are the 4 types of functions?

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.

What are the 3 types of functions?

Types of FunctionsOne – one function (Injective function) Many – one function. Onto – function (Surjective Function) Into – function.


1 Answers

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 
like image 50
Jon Skeet Avatar answered Oct 23 '22 18:10

Jon Skeet