tags:

views:

80

answers:

2

I'm trying to clean duplicate code. The only difference are calls like

MyType x = Foo.LookupService<MyType>();

vs.

MyType x = Bar.FindService<MyType>();

So we have two mehtods of type T xxx<T>(), i.e. a method returning an instance of T given the class parameter T. How could I pass such functions as a parameter to a method that tries to find instances of different types, something like

foo([magic generics stuff] resolve)
{
     MyType x = resolve<MyType>();
     MyOtherType y = resolve<MyOtherType>();
}
+1  A: 

[magic generics stuff] = Func<TResult>

Darin Dimitrov
Thanks for your answer, it showed me that my question was too unspecific. I edited it.
Christoph
+3  A: 

In response to your updated question, I'd have to say it looks like what you'll need to do is accept a parameter that implements an interface--something like IResolver, perhaps--which in turn provides a generic Resolve<T> method:

public interface IResolver
{
    T Resolve<T>();
}

void foo(IResolver resolver)
{
    MyType x = resolver.Resolve<MyType>();
    MyOtherType y = resolver.Resolve<MyOtherType>();
}

The reason for this is that you cannot (as far as I know) pass a generic delegate as a parameter to a non-generic method. What I mean is, you cannot have this:

void foo(Func<T> resolve)
{
}

When T is a type parameter, it has to be established within the declaration, not within the parameters themselves. Hopefully that makes sense.

Dan Tao
Come to think of it, I'm not sure what good this accomplishes.
Dan Tao
Thanks for the answer, it helped me realize my question was not specific enough.
Christoph
@Christoph: I think I understand your intentions a little better now (though **real** code would always be more helpful). Take a look at my revised answer and see if it makes sense to you.
Dan Tao
The information that it's not possible to pass a generic parameter to a non-generic method was the relevant information for me. Hence, your solution with an interface seems to be the optimal solution for my problem.
Christoph