Problem calling extension method on a ViewPage

477 Views Asked by At

I created the following extension method for a ViewPage:

using System.Web.Mvc;

namespace G3Site {
    public static class ViewPage_Extensions {
        public static void Test(this ViewPage vp) {
            vp.Writer.Write("this is a test");
        }
    }
}

I then put an import statement on my aspx page

<%@ Import Namespace="G3Site" %>

I can call the Test() method through this just fine:

<% this.Test(); %>

But when I try to call it without reference to this:

<% Test(); %>

I get a compiler error:

CS0103: The name 'Test' does not exist in the current context

Does anyone have any idea why this is happening and is there a way around it?

2

There are 2 best solutions below

0
On BEST ANSWER

It is a requirement of the C# compiler that extension methods are called 'off' of an expression (such as a variable or reference to an object) per the C# language specification (section 7.6.5.2).

1
On

This isn't just a limitation of the ASP.Net MVC view, this is a general rule for extension methods in C#:

public class SomeClass
{
    public void Method()
    {
        ExtensionMethod();
    }
}

public static class Extensions
{
    public static void ExtensionMethod(this SomeClass sc) { }
}

This will not compile, as the C# compiler requires extension method to be called using an instance. Why this decision is so, is probably because of some corner case only Eric Lippert can dream up :)