Meta note: it is impossible to search for the word “this”.
I’ve just run into a strange scenario in ASP.NET where the this keyword is required. But it’s not for the purpose of resolving between local and instance variables, as you would see in a constructor.
Microsoft.Web.Mvc contains a class called ControllerExtensions, and I’m using the RedirectToAction(Expression<Action<TController>> action) overload. Maybe this is special because the overload is an extension.
RedirectToAction(c => c.Index()) won’t compile, and it says Cannot convert lambda expression to type 'string' because it is not a delegate type. Now this sounds to me like it thinks I’m using the first overload which takes a string.
this.RedirectToAction(c => c.Index()) compiles fine. I can also call it statically, passing this as the first parameter.
-
Why can’t the compiler figure out that I’m looking for the overload that takes an Expression, and use that? Because the method takes an expression of an action, and not just an action, that must be involved. I don’t understand the Expressions namespace at all, so I don’t know the purpose of using this parameter type.
-
Regardless of the answer to #1, why does simply adding
thisfix everything?
Extension methods work this way.
According to the C# spec (
7.6.5.2 Extension method invocations), extension methods are only used if the call has “one of the forms”:This basically means you always have to have something on the left of the “.” to have the compiler resolve an extension method. The
expr.portion must exist (and not bedynamic) for the compiler to look for an extension method.For example, here is a small test that demonstrates:
Note the compiler error – since we’re inside of the Test instance, you can’t call
Print()directly without usingthis.. However, we can easily dotest.Print()(orthis.Print()inside of Test).