While converting my .NET 4.5 library to .NETStandard v1.6 I ran into a failing unit test which used to pass before.
I pinpointed the problem to the following three lines of code:
ParameterExpression arg1 = Expression.Parameter( typeof( DateTime ), "arg1" );
ParameterExpression arg2 = Expression.Parameter( typeof( DateTime ), "arg2" );
var test = Expression.Subtract( arg1, arg2 );
This expression tree compiles for .NET 4.5, but throws an InvalidOperationException in .NETStandard v1.6:
The binary operator Subtract is not defined for the types 'System.DateTime' and 'System.DateTime'.
However, for both targets the following code works:
DateTime one = new DateTime();
DateTime two = new DateTime();
TimeSpan difference = one - two;
I thus would expect the expression trees to compile for .NET Core as well? Am I doing something wrong, or is this a bug in .NET Core?
It's a bug in
System.Linq.Expressionsassembly.These methods are used to find the Subtract operator method:
As you see, the
GetAnyStaticMethodpicks randomly the first "op_Subtraction" method fromDateTime, instead of looping through all available, whereDateTimehas two of such operator methods:So the code picks the wrong one that takes in
DateTimeandTimeSpan, then just fails because input types don't match.In .NET 4.5 they do search in a proper way by passing argument types: