0

Possible Duplicate:
Why is the ‘this’ keyword required to call an extension method from within the extended class

Using Visual Studio 2012

Sitefinity 5.* defines a few extension methods for System.Web.UI.MasterPage in the namespace Telerik.Sitefinity.Web.UI.

If I include a reference to that namespace, I can use one particular extension method which indicates of a page is being rendered normally, or by the internal search engine:

using Telerik.Sitefinity.Web.UI;

namespace MyWebApp
{
    public partial class MyMasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /// hide common page elements.
            /// GetIndexRenderMode() returns "Normal" if the page is being rendered
            /// normally, but not if the search engine is indexing the page.
            if (this.GetIndexRenderMode() != IndexRenderModes.Normal)
            {
                headerPlaceholder.Visible = false;
                footerPlaceholder.Visible = false;
                navigationPlaceholder.Visible = false;
            }
        }
    }
}

However, if I remove this from the if(...) statement, the compiler no longer finds the extension method.

What gives? I've never before seen a case where this was necessary, except to resolve ambiguity between class members and interface members or parameters.

Community
  • 1
  • 1
3Dave
  • 28,657
  • 18
  • 88
  • 151
  • "`this` mandatory with extension methods?" would be a better title imho. – Tim Schmelter Nov 15 '12 at 12:06
  • 1
    "this" needs for name resolving. – Hamlet Hakobyan Nov 15 '12 at 12:06
  • 2
    rather then repeat the whole point check out the answer at - http://stackoverflow.com/questions/3510964/why-is-the-this-keyword-required-to-call-an-extension-method-from-within-the-e – Kami Nov 15 '12 at 12:07
  • @HamletHakobyan I've never need that for extension methods before, as long as the module where they're defined is referenced. I'm trying to figure out why this particular situation requires it. – 3Dave Nov 15 '12 at 12:16
  • @Kami nice link - I missed that one. Closing this one as a duplicate. – 3Dave Nov 15 '12 at 12:19
  • 1
    Okay, now I can neither delete nor close my own question. Awesome. – 3Dave Nov 15 '12 at 12:20

1 Answers1

2

Every extension method is an extension of some class.
You need an instance of that class to use the extension.
In your case the extension is for an instance of a MasterPage and you use it inside a derived instance of a MasterPage. Thus you need the this

Steve
  • 213,761
  • 22
  • 232
  • 286
  • I don't get it. Normal polymorphism rules say that any object is an instance of its declared type, and the types from which that inherits. Methods declared in an ancestor are inherited. Why would this be any different for extension methods, which seem to be injected into a class at JIT, then behave like a normal method? – 3Dave Nov 15 '12 at 12:18