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.
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.