qinking126
qinking126

Reputation: 11885

please explain why this c# extension method works

I bought pro asp.net mvc2 framework book. I got stuck on page 122. I couldn't understand why it works.

I already emailed author, didnt get anything back yet. here's the code, can someone please explain to me why it works.

    public static class PagingHelpers
{
    public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
    {
        StringBuilder result = new StringBuilder();

        for (int i = 1; i <= pagingInfo.TotalPages; i++)
        {
            TagBuilder tag = new TagBuilder("a");
            tag.MergeAttribute("href", pageUrl(i));

            tag.InnerHtml = i.ToString();

            if (i == pagingInfo.CurrentPage)
                tag.AddCssClass("selected");

            result.AppendLine(tag.ToString());
        }

        return MvcHtmlString.Create(result.ToString());
    }
}

this PageLinks helper method needs 3 parameters, but later in the book, when author call it,

<%: Html.PageLinks(
      new PagingInfo { CurrentPage = 2, TotalItems = 28, ItemsPerPage = 10 },
      i => Url.Action("List", new{ page = i})
) %>

author only passed in 2 parameters, HtmlHelper html is missing, but it sitll works. I couldn't figure out why, please help, thank you.

Upvotes: 2

Views: 305

Answers (3)

The Evil Greebo
The Evil Greebo

Reputation: 7138

Since the first parameter is defined as <this Type name> as opposed to the usual the compiler knows to build it in such a way that the first parameter is automatically handled for you, and thus you only need to worry about those params if any that follow.

Upvotes: 0

SLaks
SLaks

Reputation: 887451

The first parameter to an extension method is the object it's called on. (Html in your example).

You can read more about extension methods on MSDN.

Upvotes: 7

Robert Anton Reese
Robert Anton Reese

Reputation: 555

Extension methods differ from other methods in that they are

  • Declared static
  • The first parameter is the object on which it is called
  • The first parameter is prefixed by the this keyword

Further discussion can be found here: http://msdn.microsoft.com/en-us/library/bb383977.aspx

Upvotes: 1

Related Questions