I'm a bit confused about how extension methods work.
If I'm reading this correctly http://msdn.microsoft.com/en-us/library/bb383977.aspx and this If an extension method has the same signature as a method in the sealed class, what is the call precedence?.
Then the following should write out "Instance", but instead it writes "Extension method".
interface IFoo
{
}
class Foo : IFoo
{
public void Say()
{
Console.WriteLine("Instance");
}
}
static class FooExts
{
public static void Say(this IFoo foo)
{
Console.WriteLine("Extension method");
}
}
class Program
{
static void Main(string[] args)
{
IFoo foo = new Foo();
foo.Say();
}
}
Appreciate any help in clarifying the behavior.
In your
Main
,foo
is declared asIFoo
. When the compiler looks for a methodSay
, it finds only the extension method. This is because the instance method is declared inFoo
, not inIFoo
. The compiler doesn't know that the variablefoo
happens to contain a instance ofFoo
; it just looks at the type the variable is declared of.The big difference here is that you have defined an extension method for the
IFoo
interface, and yourfoo
variable is of typeIFoo
.If your code was to look like this:
The Foo.Say() method would be executed, not the extension method.
I wish I could give you a thorough explanation on why this is but I can only cover the basic mechanism. As your variable was of
IFoo
type and not ofFoo
, when the compiler tried to determine what methods were available, it looked past any non-interface methods of theFoo
class (as it should). However, the extension methodSay()
was available, so it invoked this.