Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use "this" in Extension Methods?

Tags:

c#

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.

like image 949
Mohamad Alhamoud Avatar asked Apr 04 '10 12:04

Mohamad Alhamoud


People also ask

Why we use this keyword in extension method?

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.

What is this in extension method?

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.

How do you write an extension method?

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.

Why extension methods are static?

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.


2 Answers

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.

like image 52
Matti Virkkunen Avatar answered Oct 07 '22 22:10

Matti Virkkunen


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.

like image 27
Marc Gravell Avatar answered Oct 07 '22 20:10

Marc Gravell