tags:

views:

452

answers:

4

Hi all,

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

Thanks in advance

+6  A: 

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

Here is an example of its usage:

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();
    }
}
Andrew Hare
Thanks andrew. Did you mean to write func(1) instead of bar(1)?
zSysop
Yes I did! Thanks for the correction!
Andrew Hare
+10  A: 

MSDN is your friend:

http://msdn.microsoft.com/en-us/library/bb549151.aspx

They have good examples on how to use it.

Edit: I am not trying to post this as a RTFM. Sometimes I find the easiest explanation for something is to look at the MSDN article. - JH

Jason Heine
Google's gettin' jealous now!
Cerebrus
Please, this is just a friendlier RTFM. It's not what we do here.
C. Ross
This is not a Read the * Manual. Not trying to be unfriendly, but some people don't know about MSDN (believe it or not).
Jason Heine
I don't see this fully as a RTFM response. Jason is correct that there are some developers who are new to C# and or VB who may not be fully aware of what MSDN has to offer. A RTFM response would be more along the line of "check MSDN" with no direct link, or just "google it".
David Yancey
This is easily the best explanation here.
TheSoftwareJedi
I am finding agreement with what David and SoftwareJedi say about this. I read the article and learn a lot from it.
SoftwareJedi, why is this the best explanation? I can't see what it means till I click through. The top answer has everything I need right in front of me.
C. Ross
+18  A: 

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
Jon Skeet
"In other words, it's a delegate which represents a function taking an int argument and returning a string."Just to avoid confusion for others I will clearify that you are talking about Func<int, string> here and not Func<T, TResult>.It is obvious if you understand generic types and delegates but for those who dont it is Func<int, string> that kan delegate to a function that takes a int argument and returns a string.
The real napster
Will clarify when I'm back on a PC later.
Jon Skeet
Downvoters: please provide reasons...
Jon Skeet
I think this actually is not as clear as MSDN's description and example. I also think you should add information about how the last type param is the return type - clarifying that Func<int, int, string> returns string and takes 2 ints. That helps clarify. Nothing personal - I just didn't think it was clear enough.
TheSoftwareJedi
So are you going to downvote every answer which you deem to be not as helpful as your particular favourite? Is this answer actively *unhelpful*, do you think? Do you think that perhaps having more than one way of looking at things might not be a bad idea?
Jon Skeet
Thanks jon this helped clarify certain things that were confusing to me.
zSysop
Cool. Out of interest, could you share the exact points of confusion? That could help make further explanations even clearer - because anything that you find confusing is likely to be confusing others too.
Jon Skeet
@Jon Skeet: I voted up 2 answers on this page, and down one. I found this answer unclear in parts - as I already stated. I'm not gaming the answers here. I don't feel like it's necessary to explain or reveal my voting to anyone in the community. If you have an issue about how the community works, I suggest you post it on UserVoice. Requiring user comments on downvotes has been rejected several times - go look at the reasons there, and don't take my actions so personal.
TheSoftwareJedi
@TheSoftwareJedi: No, of course, no reason to take your downvote personally - the fact that you *did* downvote for personal reasons on Saturday and then just *happened* to come into this thread after we've been having a long discussion on email about appropriate behaviour is *entirely* coincidental, isn't it?
Jon Skeet
+4  A: 

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 made up a function that eats ints and returns strings. How would 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 that's the simple idea that a lot of tricks are based upon. Now, let's use a 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 on each member, I created a reference to it called fnc (these references to methods are called delegates) and used that instead. (Remember fnc eats ints and returns strings).

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

One of the best primers on this stuff I've seen is here. He's got a lot more real examples. :)

JP Alioto
I like this explanation
The real napster