Func explanation

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

+73
c # func
May 18 '09 at
source share
3 answers

Do you know delegates in general? I have a page about delegates and events that can help if not, although it is more focused on explaining the differences between them.

Func<T, TResult> is just a general delegate - find out what this means in any particular situation by replacing type parameters ( T and TResult ) with the corresponding type arguments ( int and string ) in the declaration. I also renamed it to avoid confusion:

 string ExpandedFunc(int x) 

In other words, Func<int, string> is a delegate, which is a function that takes an int argument and returns a string .

Func<T, TResult> often used in LINQ, both for predictions and for predicates (in the latter case, TResult always bool ). For example, you can use Func<int, string> to project a sequence of integers into a sequence of strings. Lambda expressions are commonly used in LINQ to create the appropriate 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 
+122
May 18 '09 at 16:53
source share

A Func<int, string> eats ints and returns strings. So what eats ints and returns strings? How about this ...

 public string IntAsString( int i ) { return i.ToString(); } 

There I just created a function that eats ints and returns strings. How will I use it?

 var lst = new List<int>() { 1, 2, 3, 4, 5 }; string str = String.Empty; foreach( int i in lst ) { str += IntAsString(i); } // str will be "12345" 

Not very sexy, I know, but this is a simple idea on which many tricks are based. Now use Func instead.

 Func<int, string> fnc = IntAsString; foreach (int i in lst) { str += fnc(i); } // str will be "1234512345" assuming we have same str as before 

Instead of calling IntAsString for each element, I created a link to it with the name fnc (these method links are called delegates ) and are used instead. (Remember that fnc eats ints and returns strings).

This example is not very sexy, but the ton of smart things you will see is based on the simple idea of ​​functions, delegates, and extension methods .

One of the best primers on this material that I have seen is here . He got much more real examples. :)

+33
May 18 '09 at 17:18
source share

This is a delegate that takes one int as a parameter and returns a value of type string .

Here is an example of its use:

 using System; class Program { static void Main() { Func<Int32, String> func = bar; // now I have a delegate which // I can invoke or pass to other // methods. func(1); } static String bar(Int32 value) { return value.ToString(); } } 
+22
May 18 '09 at 4:48 PM
source share



All Articles