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
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:
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'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
In order to identify the method as an extension method. How else would the compiler know?
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.
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.
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.