Derived class contains a "Count" method which perform some actions on class "Derived".On the other hand i have an Extension Method which is also targets the class "Derived".
Derived derived = new Derived();
derived.Count();
By calling above snippet will execute "Count" method inside the derived class. Why C# compiler not warns and identify the Extension Method in this situation. How framework internally handling 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();
}
}
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The only advantage of extension methods is code readability.
An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.
Adding extension methods to any type is a great way to improve productivity and simplify code. You should do this wherever it feels beneficial to you, without worrying about any of these details.
The spec (§7.6.5.2) explicitly says that instance methods take priority over extension methods:
if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation.
...
The preceding rules mean that instance methods take precedence over extension methods, that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive. For example:
If an instance method matches the parameters passed, extension methods aren't even considered.
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