Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Optional generic typed parameters cannot be inferred

I had a method definition like this:

public List<TEntity> GetAll<T> (
    params Expression<Func<TEntity, T>>[] fieldsToExclude )
{
    ...
}

But when I make it like this I can't have different types.

So I have changed it to this:

public List<TEntity> GetAll<T1, T2, T3, T4, T5, T6, T7, T8> (
    Expression<Func<TEntity, T1>> field1ToExclude,
    Expression<Func<TEntity, T2>> field2ToExclude = null,
    Expression<Func<TEntity, T3>> field3ToExclude = null,
    Expression<Func<TEntity, T4>> field4ToExclude = null,
    Expression<Func<TEntity, T5>> field5ToExclude = null,
    Expression<Func<TEntity, T6>> field6ToExclude = null,
    Expression<Func<TEntity, T7>> field7ToExclude = null,
    Expression<Func<TEntity, T8>> field8ToExclude = null )
{
    ...
}

And I try to use it like:

var allItems = GetAll(p => p.SomeProperty1, p => p.SomeProperty2);

But now on client side it says:

Type arguments '...' cannot be inferred from the usage.

It makes sense since I don't use the optional paramters at all. When I give all parameters it works fine, but optionality makes it erroneous.

Creating many methods with a telescoping parameters is a way out. But there must be a neater way too I suppose. How can I provide this functionality?

Upvotes: 1

Views: 112

Answers (1)

haim770
haim770

Reputation: 49095

Since you can settle with your expressions returning Object, you can simply omit the generic argument and use Object instead:

public List<TEntity> GetAll<TEntity> (params Expression<Func<TEntity, Object>>[] fieldsToExclude)
{
    ...
}

Upvotes: 1

Related Questions