Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method vs parent class method behaviour

Look at the following code:

class A
{
    public string DoSomething(string str)
    {
        return "A.DoSomething: " + str;
    }
}

class B : A
{
}

static class BExtensions
{
    public static string DoSomething(this B b, string str)
    {
        return "BExtensions.DoSomething: " + str;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new A();
        var b = new B();
        Console.WriteLine(a.DoSomething("test"));
        Console.WriteLine(b.DoSomething("test"));

        Console.ReadKey();
    }
}

The output of the code is:

A.DoSomething: test

A.DoSomething: test

When it compiles it gives no warnings.

My questions are: why there are no warnings when that code compiles and what exactly happens when the DoSomething method is called?

like image 237
bniwredyc Avatar asked Feb 01 '26 00:02

bniwredyc


1 Answers

What happens when the method is called is simple: just instance method call. Since C# is early-bound, all methods are resolved at compile-time. In addition, instance methods are preferred over extension ones, so this is why your extension method never gets invoked.

See this:

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

In other words, if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

like image 111
Anton Gogolev Avatar answered Feb 02 '26 13:02

Anton Gogolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!