Kassem Kassem - 1 month ago 13
C# Question

Polymorphism Through Extension Methods?

I have a class library which contain some base classes and others that are derived from them. In this class library, I'm taking advantage of polymorphism to do what I want it to do. Now in a consuming application, I want to change the behavior of some code based on the runtime type of the child classes. So assume the following:

public class Base { }
public class Child1 : Base { }
public class Child2 : Base { }


Now in the consuming application I want do something as follows (note that all of the following classes are in the consuming application and cannot be referenced in the class library):

public interface IMyInterface1 { }
public interface IMyInterface2 { }
public static class Extensions
{
public static void DoSomething(this Base myObj, Object dependency)
{

}

public static void DoSomething(this Child1 myObj, Object dependency)
{
IMyInterface1 myInterface = dependency as IMyInterface1;
if (myInterface != null)
{
//Do some Child1 specific logic here
}
}

public static void DoSomething(this Child2 myObj, Object dependency)
{
IMyInterface2 myInterface = dependency as IMyInterface2;
if (myInterface != null)
{
//Do some Child2 specific logic here
}
}
}


UPDATE:

This does not work. It always calls the extension method of the base class. Is there some other way that will allow me to do this and avoid having to explicitly check for the runtime type? The reasons is because more classes that are derived from the
Base
could be added and corresponding extension methods could come from some other external assembly.

Thanks in advance.

Answer

As @SLaks has already stated you cannot call the method as an extension method (even with a dynamic type) ... you can however call the static method with a dynamic type

So, although this will fail

Base base1 = new Child1();
(base1 as dynamic).DoSomething();

This will work

Base base1 = new Child1();
Extensions.DoSomething(base1 as dynamic);