Can someone explain what the C# "Func<T,T>" does?

delete picture delete · Mar 15, 2011 · Viewed 29.1k times · Source

I'm reading the Pro MVC 2 book, and there is an example of creating an extension method for the HtmlHelper class.

Here the code example:

public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int,string> pageUrl)
{
    //Magic here.
}

And here is an example usage:

[Test]
public void Can_Generate_Links_To_Other_Pages()
{
    //Arrange: We're going to extend the Html helper class.
    //It doesn't matter if the variable we use is null            
    HtmlHelper html = null;

    PagingInfo pagingInfo = PagingInfo(){
        CurrentPage = 2,
        TotalItems = 28,
        ItemsPerPage = 10
    };

    Func<int, String> pageUrl = i => "Page" + i;

    //Act: Here's how it should format the links.
    MvcHtmlString result = html.PageLinks(pagingInfo, pageUrl);

    //Assert:
    result.ToString().ShouldEqual(@"<a href=""Page1"">1</a><a href=""Page2"">2</a><a href=""Page3"">3</a>")           

}

Edit: Removed part that confused the point of this question.

The question is: Why is the example using Func? When should I use it? What is Func?

Thanks!

Answer

jason picture jason · Mar 15, 2011

A Func<int, string> like

Func<int, String> pageUrl = i => "Page" + i;

is a delegate accepting int as its sole parameter and returning a string. In this example, it accepts an int parameter with name i and returns the string "Page" + i which just concatenates a standard string representation of i to the string "Page".

In general, Func<TSource, TResult> accepts one parameter that is of type TSource and returns a parameter of type TResult. For example,

Func<string, string> toUpper = s => s.ToUpper();

then you can say

string upper = toUpper("hello, world!");

or

Func<DateTime, int> month = d => d.Month;

so you can say

int m = month(new DateTime(3, 15, 2011));