I have a set of some classes which are all capable of being constructored with an argument being an instance of a particular interface. Since they all can be constructed by this same object (and the process during which this construction happens is largely the same in all cases), I figured perhaps templating would work. Basically, I want to do something like this:
public static void dostuff<T, U> (List<T> items) { foreach (T item in items) { func(new U(item).SpecialMember); } }
Of course, that won’t compile since U is templated and thus lacks SpecialMember as well as the T constructor.
Basically, any given implementation of the inteface T has certain features. U is an implementation of T which has an additional feature that is needed *and* which can be constructed from an any instance ofU`.
Advice?
Unfortunately while constraints will get you some of the way there, there’s no way to specify that a type has a constructor which takes certain argument: the only constructor you can require is a parameterless one.
Personally I’d like to see that change using an idea of ‘static interfaces’ (only usable for type constraints) but for the moment the best you’ll get is a type factory or reflection – or possibly a parameterless constructor and an ‘Init’ method in the interface. None of these are nice options, frankly.