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.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
The big difference here is that you have defined an extension method for the IFoo
interface, and your foo
variable is of type IFoo
.
If your code was to look like this:
Foo foo = new Foo();
foo.Say()
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 of Foo
, when the compiler tried to determine what methods were available, it looked past any non-interface methods of the Foo
class (as it should). However, the extension method Say()
was available, so it invoked this.
In your Main
,
foo
is declared as IFoo
. When the compiler looks for a method Say
, it finds only the extension method. This is because the instance method is declared in Foo
, not in IFoo
. The compiler doesn't know that the variable foo
happens to contain a instance of Foo
; it just looks at the type the variable is declared of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With