Invoking an extension method that works on a interface from an implementor seems to require the use of the this keyword. This seems odd.
Does anyone know why?
Is there an easier way to get shared implementation for an interface?
This irks me as I'm suffering multiple inheritance/mixin withdrawl.
Toy example:
public interface ITest
{
List<string> TestList { get; }
}
public static class TestExtensions
{
private const string Old = "Old";
private const string New = "New";
public static void ManipulateTestList(this ITest test)
{
for (int i = 0; i < test.TestList.Count; i++)
{
test.TestList[i] = test.TestList[i].Replace(Old, New);
}
}
}
public class Tester : ITest
{
private List<string> testList = new List<string>();
public List<string> TestList
{
get { return testList; }
}
public Tester()
{
testList.Add("OldOne");
testList.Add("OldTwo");
// Doesn't work
// ManipulateTestList();
// Works
this.ManipulateTestList();
}
}
I asked this exact question to the language team directly. I don't have the e-mail to hand, but basically the answer (from Mads, IIRC) was that it is:
Personally, I'd have liked it to work consistently - the first doesn't seem a big problem (but then, I don't write compilers), and neither approaches the fact that normally this.*
is an optional thing (that may have influences such as local code style guidelines, i.e. "thou shalt use this.
").
The relevant section in the language specification says:
7.6.5.2 Extension method invocations
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. If expr or any of the args has compile-time type
dynamic
, extension methods will not apply.
This clearly says that extension methods can only be invoked on an expression (expr). This expression can, of course, be “this
”, but it must be present.
Extension methods are a compiler trick that work on an object that redirect the call to a static method in another static class. 'this. is the object, that the compiler passes the static method. The non working example is simply the compiler telling you that the method is not and instance method scoped to the class.
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