Hi @clmcgov , Welcome to Microsoft Q&A,
Calling foo.ExtensionMethod() will print "baz". This is the rule in C#, not just a coincidence.
Extension methods are provided through static classes, but they are called as if they were instance methods of an object. When the C# compiler processes extension methods, it resolves them according to the following rules:
Compile-time type: The compiler first looks at the compile-time type of the object on which the method is called, not the runtime type. Most specific extension method first: If there are multiple extension methods whose signatures match the call, the compiler chooses the most specific type. In other words, if there are two extension methods, one for an interface type (IFoo) and another for a concrete type (Foo), the compiler chooses the one that best matches the concrete type. Explain the code
const Foo foo = new();
foo.ExtensionMethod();
In this line of code, foo is of type Foo, and the compiler first looks for an extension method that matches the type of Foo. The extension method ExtensionMethod(this Foo foo) is the most specific match, so it is selected, printing "baz". If you declare foo as type IFoo:
const IFoo foo = new Foo();
foo.ExtensionMethod();
Here, foo is of type IFoo, and the compiler selects the extension method ExtensionMethod(this IFoo foo), so it prints "bar".
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.