2

I am following along in an ASP.NET MVC book. This is one of the unit tests:

    [TestMethod]
    public void Can_Generate_Page_Links()
    {
        // arrange
        HtmlHelper myHelper = null;

        PagingInfo pagingInfo = new PagingInfo
        {
            CurrentPage = 2,
            TotalItems = 28,
            ItemsPerPage = 10
        };
        Func<int, string> pageUrlDelegate = i => "Page" + i;

        // act 
        MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate);

        // assert
        Assert.AreEqual(result.ToString(), 
            @"<a href=""Page1"">1</a>" + 
            @"<a href=""Page2"">2</a>" +
            @"<a href=""Page3"">3</a>"
        );
    }

Notice how myHelper is set to null and then used? The only code that does anything to HtmlHelper is this extension method:

    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.Append(tag.ToString());
        }

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

Does the extension method have something to do with allowing us to use an object that was set to null? If not, what is happening here?

user1873073
  • 3,580
  • 5
  • 46
  • 81

1 Answers1

3

You are correct.

Only because extension methods are syntactic sugar. When compiled, it is essentially a call like this:

YourStaticClass.PageLinks(myHelper, pagingInfo, pageUrlDelegate);

Notice in the PageLinks method, the html parameter is never used. If it were, it would throw a NullReferenceException.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138