开发者

Why we use "this" in Extension Methods?

I want to ask why we use "this" keyword before the parameter in an extension method (C# Language)........... like this function :

    public static int ToInt(this string number)
    {
        return Int32.Parse(number);
    }

I know that we have to use it but I don't know 开发者_运维技巧why.


Because that's the way you tell the compiler that it's an extension method in the first place. Otherwise it's just a normal static method. I guess they chose this so they didn't have to come up with a new keyword and potentially break old code.


For info, the significance of this as a contextual-keyword here is largely that it avoids introducing a new keyword. Whenever you introduce a new keyword you risk breaking code that would have used it as a variable / type name. this has a few useful features:

  • it is close enough to indicating that this relates to an instance method
  • it is an existing keyword...
  • ...that would have been illegal when used in that location

This means that no existing code will be broken.

Beyond the choice of this as the keyword, it is just a convenient syntax for the compiler, and more convenient than adding [Extension] manually. Without either, it would just be a static method, without any special behaviour.


It simply marks it as an extension method, this is the format they chose to go with to define the method as an extension method, as opposed to a plain static method (which is how it's called internally anyway). This is only for the compiler (and intellisense), under the covers your code compiles the same as if you were just calling the static method directly.

This definition for a method:

public static int ToInt(string number) //non extension

Needed to be distinguishable from this:

public static int ToInt(this string number) //extension

Otherwise you'd have intellisense containing every static method in a static class in included namespaces, very undesirable.


Mainly because it is how the C# spec defines an extension method. See Section 10.6.9

10.6.9 Extension methods

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.


In order to identify the method as an extension method. How else would the compiler know?


It's just the syntax that was chosen to indicate an extension method. Here's an interesting view point on the extension method syntax differences between C# and vb.net: Extension Method Implementation differences between C# and VB.NET

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜