Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Extension Method behaves different?

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();
    }
}
like image 810
Vimal CK Avatar asked Aug 11 '13 19:08

Vimal CK


People also ask

Why extension methods are static?

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.

What is an advantage of using extension methods?

The only advantage of extension methods is code readability.

Are extension methods always static?

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.

Are extension methods good practice?

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.


1 Answers

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.

like image 87
SLaks Avatar answered Sep 30 '22 15:09

SLaks