5

Consider this class:

public class Thing {

    public string Color { get; set; }

    public bool IsBlue() {
        return this.Color == "Blue";   // redundant "this"
    }

}

I can omit the keyword this because Color is a property of Thing, and I'm coding within Thing.

If I now create an extension method:

public static class ThingExtensions {

    public static bool TestForBlue(this Thing t) {
        return t.Color == "Blue";
    }

}

I can now change my IsBlue method to this:

public class Thing {

    public string Color { get; set; }

    public bool IsBlue() {
        return this.TestForBlue();   // "this" is now required
    }
}

However, I'm now required to include the this keyword.

I can omit this when referencing properties and methods, so why can't I do this...?

public bool IsBlue() {
    return TestForBlue();
}
BG100
  • 4,481
  • 2
  • 37
  • 64

2 Answers2

14

I can omit this when referencing properties and methods, so why can't I do this...?

It's just part of how extension methods are invoked, basically. Section 7.6.5.2 of the C# specification (Extension Method Invocations) starts:

In a method invocation (7.5.5.1) of one of the forms

expr . identifier ( )
expr . identifier ( args )
expr . identifier < typeargs > ( )
expr . identifier < typeargs > ( args )

if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation.

Without the this, your invocation wouldn't be of that form, so that section of the spec wouldn't apply.

This isn't a justification of why the feature was designed that way, of course - it's a justification of the compiler's behaviour in terms of correctness.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Because you need to invoke which extension method type is it gonna call, since the Extension is defined as Thing, the object needs to call itself and the static method that was defined for it.

123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • 1
    The C# specs could have easily checked the calling class (and base classes) and checked for us. They just didn't. I can only assume at some point they will add this in for us. – user441521 Aug 17 '16 at 21:17