I have the following extension methods:
public static IFoo Foo(this IFluentApi api, Action action);
public static IFoo<TResult> Foo<TResult>(
this IFluentApi api, Func<TResult> func);
public static IBar Bar(this IFoo foo);
public static void FooBar(this IBar bar, Action action);
public static void FooBar<TResult>( // <- this one cannot work as desired
this IBar bar, Action<TResult> action);
The generic interfaces are always derived from their corresponding non-generic interface.
Unfortunately, to make this work:
api.Foo(x => ReturnLong())
.Bar()
.FooBar(x => ...); // x should be of type long
I need to also implement the following extension method:
public static IBar<TResult> Bar<TResult> (this IFoo<TResult> foo);
and change the last of the above extension methods to:
public static void FooBar<TResult>(
this IBar<TResult> bar, Action<TResult> action);
As I actually not only have Bar()
between Foo()
and FooBar()
but a VERY long chain of methods I would have huge additional implementation costs.
Is there any way to avoid this problem and "magically" forward the TResult
generic parameter?
Edit:
Without losing type inference!
public static IBar<T> Bar (this IFoo<T> foo);
? – LithologyTResult
is defined once at a class level. (doing so I suppose would mean ditching the extension method usage though, and still require you to implement the methods) I say just bite the bullet, do it proper and avoid "magic". EDIT: Sorry, I think I fully understand the problem now. You need to chain the generic information across non-generic calls. Yeah, try making a separate builder class. – MelodyUnit
type as the T. TheUnit
type is the type with only one value, which can be implemented aspublic struct Unit {}
. You'll also notice that the compiler can't discern between overloads ofAction
andFunc<>
or betweenAction<T>
andFunc<T,>
, so you'll want to rename one of theFoo
s. – Prochronism