curiousDev
curiousDev

Reputation: 437

Extension Method not clear in the following program

I have the following program which i found in my learning. I am not understanding the output in which why Class3 and class4 method calling differs from class1 and class2. I see no difference in all the four classes. And how come class1 and class2 calls extension method automatically?

using System;

class Class1 {
}

class Class2 {
    public void Method1(string s) {
        Console.WriteLine("Class2.Method1");
    }
}

class Class3 {
    public void Method1(object o) {
        Console.WriteLine("Class3.Method1");
    }
}

class Class4 {
    public void Method1(int i) {
        Console.WriteLine("Class4.Method1");
    }
}

static class Extensions {
    static public void Method1(this object o, int i) {
        Console.WriteLine("Extensions.Method1");
    }

    static void Main() {
        new Class1().Method1(12); // Extensions.Method1 is called
        new Class2().Method1(12); // Extensions.Method1 is called
        new Class3().Method1(12); // Class3.Method1 is called
        new Class4().Method1(12); // Class4.Method1 is called
    }
}

Any help appreciated pls?

Upvotes: 0

Views: 15

Answers (1)

David
David

Reputation: 218828

I see no difference in all the four classes.

Look closer. Class1 has no native method at all. And the method signatures in the other three classes are all different. The method signature is key in the compiler determining which method is going to be called.


new Class1().Method1(12); // Extensions.Method1 is called

Class1 has no native Method1, so the only thing that can be called is the extension method.

new Class2().Method1(12); // Extensions.Method1 is called

Class2 does have a native Method1, but that method expects a string as an argument. An int is being provided, which is what the extension method expects. This resolves to the extension method the same as it would if there was no extension method and Class2 had two overloads, one with a string and one with an int.

new Class3().Method1(12); // Class3.Method1 is called

Class3 has a native method which expects an object. Since that is satisfied by the integer being supplied, it takes priority over the extension method.

new Class4().Method1(12); // Class4.Method1 is called

Same as Class3 above, there is a native method which is satisfied by this call. This one is even more specific, taking an int as an argument.

Upvotes: 1

Related Questions