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();
}
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
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.
It is compulsion that the Extension method must be in a Static class only so that only one Instance is created. For example, if you place the following in ASP.Net page it will not work.
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.
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.
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