public class StoreController : Controller
{
public string Index()
{
// implicitly specified instance does not work
//return GetMemberName();
// must specify this explicitly
return this.GetMemberName();
}
}
public static class Utilities
{
public static string GetMemberName(this Controller caller,
[CallerMemberName] string memberName = "")
{
return caller.GetType().FullName + "." + memberName;
}
}
Why do we have to explicitly specify this when invoking an extension method from within a method of a class being extended?
In my mental model, we usually can omit this such as when we initialize fields, for example.
Without being present at the design board meeting where this was decided it’s hard to say why it’s like that.
In this text I use method or instance method in the sense of a function associated with a specific object instance and I use function in a mathematical sense. A function receives a number of arguments and creates a result (which is potentially void)
If we do not consider virtual methods which are more complex because the actual function to be called is determined runtime then any and all method calls are syntactic sugar. If we have two methods defined below
Then both will be translated to a function call where the first (and only) argument in both cases will be the object identified by
this. If you are doubtful about this then look at the IL produced for any call to an instance method and you will notice there’s an extra argument compared to the declaration in code. This argument is thethisreference, which is always passed as the first argument to an instance method.So in the case of an instance method the compiler still need to determine which object to pass as the first argument to the function. That is exactly the same it has to do if you are calling an extension method without
thiswhich also means that can’t be the real reason why you have to usethisin front of an extension method.In the compiler for Marvin, a compiler build on top of the Mono compiler I had to do a similar trick as C# does with extension methods and wondered why the specs require the
thisThe real reason why the compiler enforces you to use
thisbefore an extension method is that the specs says so. What the reason behind that decision is would need the attention of some one like @EricLippert who where probably there when they decided on that requirement