1

I have this functionality:

 public class Repository : IRepository
    {
        public List<TEntity> GetOrdered<TEntity, TSortKey>(Func<TEntity, TSortKey> orderBy, int take, params string[] includePaths) where TEntity : AbstractEntity
        {
            var query = (from ent in this.Context.Set<TEntity>() select ent).IncludePaths(includePaths);

            return query.OrderBy(orderBy).Take(take).ToList();
        }
    }    

To invoke it:

List<Project> p = repository.GetOrdered<Project, string>(x => x.Name, 10);

I want to eliminate the need to give it the second generic parameter when invoking, it's a deal breaker from an API perspective.

How to do it?

h.alex
  • 902
  • 1
  • 8
  • 31

2 Answers2

3

it's a deal breaker from an API perspective

then consider your deal broken... You can't partially infer generic parameters. If your repository was generic you could possibly do:

 public class Repository<TEntity> : IRepository<TEntity> where TEntity : AbstractEntity
{
    public List<TEntity> GetOrdered<TSortKey>(Func<TEntity, TSortKey> orderBy, int take, params string[] includePaths) 
    {
        var query = (from ent in this.Context.Set<TEntity>() select ent).IncludePaths(includePaths);

        return query.OrderBy(orderBy).Take(take).ToList();
    }
}  

then do

List<Project> p = repository.GetOrdered(x => x.Name, 10);

But I don't know if that change is possible for you.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • It is not generic, I like it better that way, I feel it allows simpler use. Thank you for the answer, I will +1 it, but take the other one, as it works within my architecture (albeit I don't like the usage syntax). And why don't they implement partial inference? It clearly makes sense, at least in this case. – h.alex Oct 16 '14 at 22:59
  • @h.alex Because it costs money to design, build, test, and ship features. The C# team weighs the benefit of a feature versus the cost, and weighs it against the benefit of other requested features. So far it seems that the benefit isn't worth the cost. Also see [this answer](http://stackoverflow.com/a/6878596/1081897) for another opinion. – D Stanley Oct 17 '14 at 01:18
  • So MS should hire more architects, developers, and testers to build every single feature regardless of its value? Sorry, the world doesn't work that way. – D Stanley Oct 17 '14 at 13:50
1

Either the compiler can infer all type parameters, or you have to specify them all. But you may explicitly specify the argument type of the lambda expression, such as:

List<Project> p = repository.GetOrdered((Project x) => x.Name, 10);
Mathias Becher
  • 703
  • 8
  • 20
  • I didn't know I can do that with lambdas. Thank you! I don't like the usage syntax, but I guess it's the only possible way. This actually works. – h.alex Oct 16 '14 at 23:00