Why can't these generic type parameters be inferred?

Posted by Jon M on Stack Overflow See other posts from Stack Overflow or by Jon M
Published on 2010-06-07T14:19:47Z Indexed on 2010/06/07 14:22 UTC
Read the original article Hit count: 153

Filed under:
|
|

Given the following interfaces/classes:

public interface IRequest<TResponse> { }

public interface IHandler<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    TResponse Handle(TRequest request);
}

public class HandlingService
{
    public TResponse Handle<TRequest, TResponse>(TRequest request)
        where TRequest : IRequest<TResponse>
    {
        var handler = container.GetInstance<IHandler<TRequest, TResponse>>();
        return handler.Handle(request);
    }
}

public class CustomerResponse
{
    public Customer Customer { get; set; }
}

public class GetCustomerByIdRequest : IRequest<CustomerResponse>
{
    public int CustomerId { get; set; }
}

Why can't the compiler infer the correct types, if I try and write something like the following:

var service = new HandlingService();
var request = new GetCustomerByIdRequest { CustomerId = 1234 };
var response = service.Handle(request);  // Shouldn't this know that response is going to be CustomerResponse?

I just get the 'type arguments cannot be inferred' message. Is this a limitation with generic type inference in general, or is there a way to make this work?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics