1

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

I want to localization my MVC application then I want to use w(message) method and as "flem" answered here I have this code:

namespace System.Web.WebPages
{
    public static class Localization
    {
        public static string w(this WebPageBase page, string message)
        {
            return message;
        }
    }
}

but in razor page(page.cshtml) I can't use @w("hi") but @this.w("hi") works. I want to know how it is possible to this.method() works but method() doesn't work?

Community
  • 1
  • 1
ahmadali shafiee
  • 4,350
  • 12
  • 56
  • 91

3 Answers3

2

To call a static method you have to specify which class the method belongs to.

In your case, because this is an extension method this is referring to the current page which is of type WebPageBase. So this.w("hi") is effectively the same as you are writing:

@WebPageBase.w("hi")

... which is equivalent to:

@Localization.w(this, "hi")
cspolton
  • 4,495
  • 4
  • 26
  • 34
  • The method belongs to `Localization` and is an extension method. An object of type `WebPageBase` is required to call the method, which is why `this` is required. – cadrell0 Aug 31 '12 at 12:43
2

w is an extension method and the way they work is that the object you call it on is put in place of the parameter specified by this in the method signature.

In the case of this.w you are specifying the object it shoudl work on.

if you jsut call w("") then you are not specifying that first parameter.

I assume you are thinking that if it was a method of that object then the two calls would be the same and this is true. However, the difference is that there is no method in scope which is just w. That method is in another class and its only the magic of extension methods that allows it to work in the correct circumstances.

Chris
  • 27,210
  • 6
  • 71
  • 92
  • Remember that extension methods are just syntax sugar. It is the same as `Localization.w(this, "")`. Not specifying `this` would be the same as Localization.w("")`. This overload does not exist. – cadrell0 Aug 31 '12 at 12:45
  • @cadrell0: Yeah, maybe should have been more explicit but the linked duplicate just says everything that needs to be said now so I wouldn't bother editing my answer any more. :) – Chris Aug 31 '12 at 12:49
1

You have created an extension method for WebPageBase.
It should be called using an object WebPageBase or a derived object.
In your case this is the correct object to use (Probably a Page object)

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Steve
  • 213,761
  • 22
  • 232
  • 286