Why we use “this” in Extension Methods?

后端 未结 6 1258
遥遥无期
遥遥无期 2021-01-17 10:36

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

    public static int ToI         


        
相关标签:
6条回答
  • 2021-01-17 10:54

    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.

    0 讨论(0)
  • 2021-01-17 10:55

    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 讨论(0)
  • 2021-01-17 11:01

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

    0 讨论(0)
  • 2021-01-17 11:10

    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.

    0 讨论(0)
  • 2021-01-17 11:14

    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.

    0 讨论(0)
  • 2021-01-17 11:14

    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.

    0 讨论(0)
提交回复
热议问题