views:

89

answers:

3

I have the following class:

    public class MyClass<T> where T : class
    {
         public void Method1<TResult>(T obj, Expression<Func<T, TResult>> expression)
         {
             //Do some work here...
         }

         public void Method2<TResult>(T obj, Expression<Func<T, TResult>> expression1, Expression<Func<T, TResult>> expression2)
         {
             //Do some work here...
         }
    }

I can call Method1 like this:

MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();

myObject.Method1(someObject, x => x.SomeProperty);

But when I try to call Method2:

MyClass<SomeOtherClass> myObject = new MyClass<SomeOtherClass>();

myObject.Method2(someObject, x => x.SomeProperty, x => x.SomeOtherProperty);

I get the following compile-time error:

Error 1 The type arguments for method 'MyClass.Method2<SomeOtherClass>.Method2<TResult>(SomeOtherClass obj, System.Linq.Expressions.Expression<System.Func<SomeOtherClass,TResult>>, System.Linq.Expressions.Expression<System.Func<SomeOtherClass,TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

How can I make an method that accept two lambdas and call it like I intended?

+4  A: 

Have you tried using 2 type parameters instead?

Eg:

void Method2<TResult1, TResult2>(T obj, 
   Expression<Func<T, TResult1>> expression1, 
   Expression<Func<T, TResult2>> expression2)
leppie
+7  A: 

Do SomeProperty and SomeOtherProperty have the same type? If not, there's your problem, since you're using one TResult type parameter.

The solution is just to use two type parameters:

public void Method2<TResult1, TResult2>(T obj, Expression<Func<T, TResult1>> expression1, Expression<Func<T, TResult2>> expression2)
{
    //Do some work here...
}
Dan Tao
A: 

You could try specifying the type argument explicity.

myObject.Method2<string>(
  someObject,
  x => x.SomeProperty,
  x => x.SomeOtherProperty);

If that doesn't work (say SomeProperty and SomeOtherProperty are different types) you could allow for additional type information in the method declaration.

public void Method2<TResult1, TResult2>
(
  T obj,
  Expression<Func<T, TResult1>> expression1,
  Expression<Func<T, TResult2>> expression2
) 
David B