1

I have used this question to "pass a property as a parameter to a method" and change the property's value with an additional parameter. My problem is not how to accomplish that but rather the method call results in a compile error.

Call and method definition

Run(f => f.A, 15);

public static void Run<T, TValue>(Expression<Func<T, TValue>> lamdaExpression, TValue value)

I get this error:

Error CS0411: The type arguments for method Program.Run<T, TValue>(Expression<Func<T, TValue>>, TValue) cannot be inferred from the usage. Try specifying the type arguments explicitly

I have already searched on the above message and there are several examples, none are like mine. So I don't understand what is the problem.
Please help!

Additional information
I have one similar method call and method definition which don't have this problem. So I'm a bit confused.

Run(foo, f => f.A, 10);

public static void Run<T, TValue>(T obj, Expression<Func<T, TValue>> property, TValue value)

Notice this method has the same Expression<Func<T, TValue>> property and its working.

The program I've been using:

class Foo
{
    public int A {get; set; }
}

class Program
{
    public static void Main()
    {
         var foo = new Foo();

         //... Calls to the methods...
    }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Mc_Topaz
  • 567
  • 1
  • 6
  • 21
  • The type of `T` can't be inferred from the lambda expression. The second method works because the type of `T` is inferred from the first argument. – Zohar Peled Feb 27 '18 at 13:59

1 Answers1

2

The problem is that f => f.A cannot be used to infer the type of f.

So, easy fix:

Run<Foo, int>(f => f.A, 15);

Notice that if you have to specify one of the type arguments, you need to specify all of them.

Your other method works because T is inferred from the first parameter T obj

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120