I’m having some trouble understanding why the type arguments can’t be inferred from the usage below.
While the types can clearly be inferred in Build
, I’m struggling to understand why (I’m assuming) TResult
can’t be inferred for Execute
.
I’ve read similar questions, such as this one, and I understand the types are not inferred by constraints. What I can’t work out is why the compiler isn’t able to infer the return type based on the expression parameter. It can work out the type for new()
in Build
, but not for TResult
in Execute
?
I’m ware I could invoke the method with type arguments specified explicitly like so Execute<DemoCommand, DemoArgs, int>(...)
, but this is usage is undesirable and doesn’t do much to answer why it doesn’t work.
using System.Linq.Expressions;
// this works
var command = Build((DemoCommand c) => c.Args, new());
TCommand Build<TCommand, TArgs>(Expression<Func<TCommand, TArgs>> propertyExpression, TArgs propertyValue)
{
var command = Activator.CreateInstance<TCommand>();
return command;
}
// this doesn't work
var result = Execute((DemoCommand c) => c.Args, new());
TResult Execute<TCommand, TArgs, TResult>(Expression<Func<TCommand, TArgs>> propertyExpression, TArgs propertyValue) where TCommand : Command<TResult>
{
var command = Build(propertyExpression, propertyValue);
return command.Result;
}
class Command<T>
{
public T Result { get; set;}
}
class DemoCommand : Command<int>
{
public DemoArgs Args { get; set; }
}
class DemoArgs
{
}