Call extension method created on parent class overloaded in child class

  • I am having code as below where WebServiceSender is the parent class.

  • I have added an Extension method to this as "ExtTest".

  • I have one child class "ChildWebServiceSender" inheriting WebServiceSender.

  • In my child class I am having a method with same signature as Extension method, public WebServiceSender ExtTest(string something)

Now after creating object of Child class I get intellisense as there are TWO OVERLOADED methods. But I can always call ExtTest from Child class but not the Extension method.

How can I call Extension method ExtTest?

public class WebServiceSender : IMessageSender
{
    public void SendMessage(string subject, string body)
    {
        Console.WriteLine("Web Service\n{0}\n{1}\n", subject, body);
    }
}
public static class util 
{
    public static WebServiceSender ExtTest(this WebServiceSender abc, string something)
    {
        Console.WriteLine("I am into extension");
        return new WebServiceSender();
    }
}

public class ChildWebServiceSender : WebServiceSender
{
    public WebServiceSender ExtTest(string something)
    {
        Console.WriteLine("I am in instance");
        return new WebServiceSender();
    }
}

class Program
{
    static void Main(string[] args)
    {
        ChildWebServiceSender d = new ChildWebServiceSender();
        d.ExtTest("abc");
    }
}
Jon Skeet
people
quotationmark

How can i call Extension method ExtTest ?

Instance methods will always be preferred over extension methods - the compiler only checks for extension methods after everything else has failed.

In this case, the simplest approach is just to use a variable of type WebServiceSender instead:

WebServiceSender d = new ChildWebServiceSender();
d.ExtTest("abc"); // This will call the extension method

The execution-time type of d doesn't matter - only the compile-time type.

If you need to call methods from ChildWebServiceSender as well, you can just use two variables which refer to the same object:

ChildWebServiceSender child = new ChildWebServiceSender();
WebServiceSender baseRef = child;
child.ExtTest("abc"); // This will call the child instance method
baseRef.ExtTest("abc"); // This will call the extension method

(You can use a cast instead, of course - I figured this would be clearer to read. The main point is that you want an expression of type WebServiceSender as the target for the method call.)

Or you could just call the method as a regular static method:

// TODO: Rename "util" to follow .NET naming conventions
util.ExtTest(d, "abc");

Or, better, you could rename either your extension method or your instance method so that they don't conflict - that will make it clearer to anyone reading the code which you're trying to call.

people

See more on this question at Stackoverflow