3

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:

See also:

desmondgc
  • 501
  • 2
  • 9
  • 2
    Short answer: no, it's not possible. – René Vogt Dec 15 '17 at 15:21
  • No - partial parameter inference is not possible - you either specify them all or none. – D Stanley Dec 15 '17 at 15:22
  • You can only infer types on methods, when dealing with class generics you have to list them. – juharr Dec 15 '17 at 15:32
  • Outside the question you've asked, the problem can be solved changing the structure a little bit. `class Entity { public Type TypeProp { get; set;} public Entity(Type type) { TypeProp = type; } } class Entity : Entity { Entity() : base(typeof(TId)) { } } class Product : Entity { } interface IRepository where TEntity : Entity { IDictionary Get(); }` – Diego Rafael Souza Dec 15 '17 at 15:39

0 Answers0