views:

140

answers:

5

I have two interfaces IDto1 and IDto2. IDto2 inherits IDto1. Both interfaces are for DTOs and so I wish to keep "complex" code out of their implementations - I do this by putting a single extension method Initialize in a static class for each interface.

So I end up with the following types IDto1, IDto2, IDto1Extensions, IDto2Extensions.

I wish to have the Initialize extension method on both interfaces, but for each to have a different implementation.

In client code I want to use code like this:

(dto as IDto1).Initialize();

...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.

Is this possible in C# and if not why not?

Edit:

Sorry, of course this:

(dto as IDto1).Initialize();

...will invoke the Initialize method on the IDto1 type. I meant that the dto variable would be passed in as an argument to a method, under which circumstances I believe the method would be chosen polymorphically given the inheritance hierarchy I specified earlier.

Thanks for all your answers.

+3  A: 

What you are trying to achieve here is some sort of polymorphysm. Extension methods are static methods. In OOP polymorphysm is applicable only for instance methods.

An option could be to switch to abstract classes.

Vitaliy Liptchinsky
Chosen because answered question directly and offered a workaround. Other answers were great too.
Ben Aston
+3  A: 

What you are trying to accomplish is not possible because extension methods are resolved at compile time, while in your case the actual type of the dto variable is known only at runtime.

Darin Dimitrov
+4  A: 

Looking at your statement:

(dto as IDto1).Initialize();

...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.

The "resolved type" of the thing in brackets is precisely IDto1. It cannot be anything else, so that is what the compiler will work with. Indeed variables never change type (I assume you mean the object referred to by the variable's value).

In .NET 4.0 / C# 4.0, an option here for duck-typing might be an instance method and dynamic...

((dynamic)dto).Initialize();

...but to be honest I can't see why you can't just add your Initialize method to the interface and use polymorphism, since that sounds the closest to what you are trying to describe.

Marc Gravell
+1  A: 

Hi Ben!

If you want to make your code more dynamic you can define the class that you want in configuration file and use something like this

String className = ConfigurationManager.AppSettings["Interface"].ToString();

IDto1 dto = (IDto1)Activator.CreateInstance(Type.GetType(className));

In this sample I use the first line to get's the class name.

The second line create an instance of the Object.

Guilherme Ferreira http://guilhermeferreira.wordpress.com/

Guilherme Ferreira
A: 

This sounds like a job for an abstract base class.

JeffreyABecker