Let's say I have a service interface that looks like this:
public interface IFooService
{
FooResponse Foo(FooRequest request);
}
I would like to fulfill some cross-cutting concerns when calling methods on services like these; for example, I want unified request logging, performance logging, and error handling. My approach is to have a common base "Repository' class with an Invoke
method that takes care of invoking the method and doing other things around it. My base class looks something like this:
public class RepositoryBase<TService>
{
private Func<TService> serviceFactory;
public RepositoryBase(Func<TService> serviceFactory)
{
this.serviceFactory = serviceFactory;
}
public TResponse Invoke<TRequest, TResponse>(
Func<TService, Func<TRequest, TResponse>> methodExpr,
TRequest request)
{
// Do cross-cutting code
var service = this.serviceFactory();
var method = methodExpr(service);
return method(request);
}
}
This works fine. However, my whole goal of making the code cleaner is thwarted by the fact that type inference isn't working as expected. For example, if I write a method like this:
public class FooRepository : BaseRepository<IFooService>
{
// ...
public BarResponse CallFoo(...)
{
FooRequest request = ...;
var response = this.Invoke(svc => svc.Foo, request);
return response;
}
}
I get this compilation error:
The type arguments for method ... cannot be inferred from the usage. Try specifying the type arguments explicitly.
Obviously, I can fix it by changing my call to:
var response = this.Invoke<FooRequest, FooResponse>(svc => svc.Foo, request);
But I'd like to avoid this. Is there a way to rework the code so that I can take advantage of type inference?
Edit:
I should also mention that an earlier approach was to use an extension method; type inference for this worked:
public static class ServiceExtensions
{
public static TResponse Invoke<TRequest, TResponse>(
this IService service,
Func<TRequest, TResponse> method,
TRequest request)
{
// Do other stuff
return method(request);
}
}
public class Foo
{
public void SomeMethod()
{
IService svc = ...;
FooRequest request = ...;
svc.Invoke(svc.Foo, request);
}
}
The type of the x variable is inferred to be number . This kind of inference takes place when initializing variables and members, setting parameter default values, and determining function return types. In most cases, type inference is straightforward.
While type inference is really useful for local variables, it should not be used for public APIs which have to be unambiguously documented. And sometimes the types really are critical for understanding what's going on in the code. In such cases, it would be foolish to rely on type inference alone.
TypeScript infers types of variables when there is no explicit information available in the form of type annotations. Types are inferred by TypeScript compiler when: Variables are initialized. Default values are set for parameters. Function return types are determined.
The question which is the title of your question is "why isn't type inference working in this code?" Let's simply the code in question. The scenario is at its heart:
class Bar { }
interface I
{
int Foo(Bar bar);
}
class C
{
public static R M<A, R>(A a, Func<I, Func<A, R>> f)
{
return default(R);
}
}
The call site is
C.M(new Bar(), s => s.Foo);
We must determine two facts: what are A
and R
? What information do we have to go on? That new Bar()
corresponds to A
and s=>s.Foo
corresponds to Func<I, Func<A, R>>
.
Clearly we can determine that A
must be Bar
from that first fact. And clearly we can determine that s
must be I
. So we now know that (I s)=>s.Foo
corresponds to Func<I, Func<Bar, R>>
.
Now the question is: can we infer that R
is int
by doing overload resolution on s.Foo
in the body of the lambda?
Sadly, the answer is no. You and I can do that inference, but the compiler does not. When we designed the type inference algorithm we considered adding this kind of "multi-level" lambda/delegate/method group inference but decided that it was too high cost for the benefit it would confer.
Sorry, you are out of luck here; in general, inferences that would require "digging through" more than one level of functional abstraction are not made in C# method type inference.
Why did this work when using extension methods, then?
Because the extension method does not have more than one level of functional abstraction. The extension method case is:
class C
{
public static R M<A, R>(I i, A a, Func<A, R> f) { ... }
}
with a call site
I i = whatever;
C.M(i, new Bar(), i.Foo);
Now what information do we have? We deduce that A
is Bar
as before. Now we must deduce what R
is knowing that i.Foo
maps to Func<Bar, R>
. This is a straightforward overload resolution problem; we pretend that there was a call to i.Foo(Bar)
and let overload resolution do its work. Overload resolution comes back and says that i.Foo(Bar)
returns int
, so R
is int
.
Note that this kind of inference -- involving a method group -- was intended to be added to C# 3 but I messed up and we did not get it done in time. We ended up adding that kind of inference to C# 4.
Note also that for this kind of inference to succeed, all the parameter types must already be inferred. We must be inferring only the return type, because in order to know the return type, we must be able to do overload resolution, and to do overload resolution, we must know all the parameter types. We do not do any nonsense like "oh, the method group only has one method in it, so let's skip doing overload resolution and just let that method win automatically".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With