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 the extension method does not exist with the ViewPage class. You need to tell the compiler what you are calling the extension method on.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
To define and call the extension method Define a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don't have access to the source code of the type. An extension method is just like another static method but has the “this” reference as its first parameter.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With