I want to define a generic base class for entities within a system that exposes the type of the entity's identifier (e.g. int, Guid, etc.)
class Entity<TId>
{
}
class Product : Entity<int>
{
}
I can then define a generic repository interface to retrieve a dictionary of entities keyed by id.
interface IRepository<TEntity, TId> where TEntity : Entity<TId>
{
Dictionary<TId, TEntity> Get();
}
In order to use this generic interface, I must provide both type arguments:
IRepository<Product, int> productRepository;
However, this feels redundant. Is it not possible to infer the second type argument given the type constraint in the interface definition? I want to be able to write:
IRepository<Product> productRepository;
Edit: I'm bad at search, apparently. As always, I couldn't find a good explanation until after posting.
This question was marked as duplicate but I've found what I think are better resources than the linked duplicate.
The most complete explanation is Eric Lippert's blog post:
More relevant SO questions:
- Working around lack of partial generic type inference with constraints
- Type inference with interfaces and generic constraints
See also: