Why does the extension method behave differently?

The derived class contains the Count method, which performs some actions on the Derived class. On the other hand, I have an extension method that also targets the Derived class.

Derived derived = new Derived(); derived.Count(); 

Calling the fragment above, the "Count" method will be executed inside the derived class. Why the C # compiler does not warn or identify the extension method in this situation. How does the infrastructure internally handle this?

 //Base class public class Base { public virtual string Count() { return string.Empty; } } //Derived class public class Derived : Base { public override string Count() { return base.Count(); } } //Extension Methods for Derived class public static class ExtensionMethods { public static Derived Count(this Derived value) { return new Derived(); } } 
+6
source share
1 answer

The specification (ยง7.6.5.2) explicitly states that instance methods take precedence over extension methods:

if normal call processing does not find applicable methods, an attempt is made to process the construct as a call to the extension method.

...

Previous rules mean that instance methods take precedence over extension methods, that extension methods available in internal namespace declarations take precedence over extension methods available in external namespace declarations, and that extension methods declared directly in the namespace take precedence compared to extension methods imported into the same namespace using the namespace directive. For instance:

If the instance method matches the parameters passed, the extension methods are not even considered.

+6
source

Source: https://habr.com/ru/post/951501/


All Articles