How do extension methods work in C#?

I'm not entirely sure as to how to figure out if a method is an extension method or not. I read the following guidelines:

  1. The method has to be in a static class (for example "IntExtensions").

  2. The method needs to be "public static" (for example public static int Half(this int source))

My issues with the extension methods are:

  1. I don't understand is how we know which class the method is extending. Is it the class that has this preceding it? So in the example above it would be string?
  2. What role does the static class that encloses the method play? The whole syntax seems very confusing.
  3. couldn't I group a number of different extension methods for different classes under the same class ( which doesn't seem to make sense since I want to extend only 1 class ) For example:

/

public static class IntExtensions 
{
    // method has to be static, first parameter is tagged with the 'this'
    // keyword, the type of the parameter is the type that is extended.
    public static int Half(this int source) 
    {
        return source / 2;
    }

    public static string foo( this string s)
    {
        //some code
    }
}
Jon Skeet
people
quotationmark

I don't understand is how we know which class the method is extending. Is it the class that has this preceding it?

Yes. It's always the first parameter of the method. You can't decorate any other parameter with this. (And it's the fact that this is present which tells the compiler that you're trying to write an extension method.)

What role does the static class that encloses the method play? The whole syntax seems very confusing.

It's just a class to "house" the extension method. Frequently extension methods don't use any other members of the class in which they're written, although they can. (For example, an extension method can use a private static field within the static class enclosing it.)

In many ways - including this one - an extension method is just a normal static method. It has to be in a top-level static non-generic class, and the first parameter can't be out or ref, but once those conditions are satisfied, it's just a normal method as far as the method implementation is concerned. It's "special" as far as callers are concerned, in terms of how you can invoke the method. (It can be invoked in the same way as any other static method as well, mind you.)

couldn't I group a number of different extension methods for different classes under the same class ( which doesn't seem to make sense since I want to extend only 1 class )

Yes, you can. It's not usually a good idea, but you can absolutely do that.

people

See more on this question at Stackoverflow