Possible Duplicate:
Why is the 'this' keyword required to call an extension method from within the extended class
I have an extension method declared in an assembly under a certain namespace, it’s a very common helper:
using System;
namespace Common {
public static class GenericServiceProvider {
public static T GetService<T>(this IServiceProvider serviceProvider) {
return (T)serviceProvider.GetService(typeof(T));
}
}
}
Now in a different assembly and namespace, I’m trying to access this extension method from a class that implements IServiceProvider:
using System;
using Common;
namespace OtherNamespace {
class Bar: IServiceProvider {
void Foo() {
GetService<IMyService>(); // doesn't compile
this.GetService<IMyService>(); // compiles
}
}
}
As you can see, I cannot call the generic extension method directly, it doesn’t even show up in IntelliSense. However, if I add “this” before the call, it works fine.
This is in Visual Studio 2010 using .NET 4.
Is this normal or am I doing something wrong? Thanks.
This is normal. The extension method has to extend something. The compiler won’t search for extension methods unless there is something as the “expression” (to the left of the .”). This is defined in the C# language spec, 7.6.5.2:
Basically, you always need something for expr. In this case,
thisworks, and the compiler can rewrite this as: