12/29/2010
Partial Type Inference in .Net

When designing fluent APIs, one issue that comes up is partial type inference. If a method has two type parameters, there is no way to call it and only specify one of the type parameters (and leave the other inferred by the compiler)

For example, suppose we are creating a type-safe wrapper around a parameterized SqlCommand. Ideally, it would be called like this:

In order to implement this efficiently, one would create methods at runtime which add DbParameters for each property in the anonymous type, and store them in a static generic class. It would look something like this:

However, that requires that the ExecuteScalar extension method take TParam as a generic parameter. Since anonymous types can only be passed as generic parameters via type inference, this makes it impossible to pass the return type as a generic parameter.

To fix this issue, we can split the generic parameters across two methods. We can change the extension method to take a single generic parameter, and return a generic class with a method that takes the other generic parameter.

I use an IHideObjectMembers interface to hide the methods inherited from Object from IntelliSense. Note that the interface must be defined in an assembly outside of your solution. (or, to be more precise, that isn’t a Project reference)