Given interface
public interface IHaveError
{
string ErrorMessage { get; set; }
}
Extension
public static class HaveErrorExtensions
{
public static void SetErrorMessage(this IHaveError target, string message)
{
target.ErrorMessage = message;
}
}
Class
public class HaveError : IHaveError
{
public string ErrorMessage { get; set; }
public void DoSomething()
{
this.SetErrorMessage(message);
}
}
Why is this. required on the call to the extension method? The name is not resolved without it.
This is how extension methods work in the C# language spec. If you read section “7.6.5.2 Extension method invocations”, it basically says that you must have a method invocation of one of the following forms:
If you note,
expris required for an extension method search to be an option.In this case,
this.becomes theexpr.above, so that the above can get translated into the static method invocation for a type where it’s an extension method defined as:In your case, in order for the compiler to “find” (or even search for) the method call, you need to have some “expr” type specified. The explicit
this.qualifies. It causes the compiler to take this:And search for a matching extension method that works with the type, translating it into: