1

I made a generic Repository class with a GetById method

public interface IEntity<T>
{
    public T Id { get; set; }
}
...
public Product: IEntity<int>
{
    public int Id { get; set; }
}
...
public Task<T> GetById<T, TId>(TId id) where T : class, IEntity<TId>
{
    return dbContext.Set<T>().FirstOrDefaultAsync(x => x.Id.Equals(id));
}

I want the type be inferred from the parameter when i call it

myRepo.GetById<Product>(pId) //compile error (I want this to work)
myRepo.GetById<Product,int>(pId) //works

I thought the second generic could be inferred from the parameter. Am I missing something or is it not possible?

Rodrigo
  • 19
  • 1
  • "I want this to work" -it will not cause current strategy is "all or nothing" - either all is inferred or nothing. But maybe it will change [in future](https://github.com/dotnet/csharplang/issues/1349). – Guru Stron Jan 22 '22 at 21:54
  • Is that repository really generic? And by this I mean, is the class declared with generic parameters, like `public class Repository`? I suspect it is not, but if you made it generic like that, you might get your GetById method working as well. – Lasse V. Karlsen Jan 22 '22 at 22:00

0 Answers0