0

I have a question regarding generic methods with two generic arguments. Imagine this:

public class A
{
    public string PropertyA {get;set;}
}

---------------------------------------------------------------------------

private string GetProperty<T, P>(Expression<Func<T, P>> expressionProperty)
    where T : class
{
    return ((MemberExpression)expressionProperty.Body).Member.Name;
}

---------------------------------------------------------------------------

void Main()
{
    GetProperty<A>(x => x.PropertyA).Dump();
}

This won't compile:

CS0305 Using the generic method 'UserQuery.GetProperty(Expression>)' requires 2 type arguments

So I have to call the method like this:

void Main()
{
    GetProperty<A,string>(x => x.PropertyA).Dump();
}

Why can't the compiler infer the PropertyA type?

Pedro Faustino
  • 227
  • 3
  • 14

1 Answers1

1

Because you need to pass all generic parameters explicitly or 0 parameters so the compiler can infer all of them. Interfering doesn't work partially. However you can do this:

void Main()
{
    GetProperty((A x) => x.PropertyA).Dump();
}
MistyK
  • 6,055
  • 2
  • 42
  • 76
  • Now I get it. I've also tested creating an extension method and that way I could call a.GetProperty(x => x.PropertyA); But like you said, this way I pass 0 parameters. Btw, your example fits perfectly in what I was trying to achieve (which is not having to pass the parameter type) – Pedro Faustino Oct 04 '18 at 13:44