System.Linq.Dynamic.Core icon indicating copy to clipboard operation
System.Linq.Dynamic.Core copied to clipboard

C# Expressions use Base Class Virtual Methodinfo

Open jogibear9988 opened this issue 3 years ago • 8 comments

If you write a Expression where you call a Virtual Method, the C# Expression Parser uses the MethodInfo from the BaseClass where System.Dynamic.Linq uses the MethodInfo from the Derived Class.

see issue: https://github.com/linq2db/linq2db/issues/3475

jogibear9988 avatar Mar 21 '22 16:03 jogibear9988

This will be fixed in linq2db, but ,aybe will also fail in other Linq Frameworks

jogibear9988 avatar Mar 22 '22 16:03 jogibear9988

@jogibear9988

  • Do you have any lead where this should be fixed in the code ?
  • Or maybe create a PR with unit tests?

StefH avatar Mar 22 '22 16:03 StefH

If I understand correctly, the following code:

using System.Linq.Expressions;
using static System.Console;
using static System.Linq.Expressions.Expression;
using System.Linq.Dynamic.Core.Parser;
using System.Linq.Dynamic.Core;

Expression<Func<int?, string?>> expr = x => x.ToString();
WriteLine(
    ((MethodCallExpression)expr.Body).Method.DeclaringType
);

var selector = "ToString()";
var prm = Parameter(typeof(int?));
var parser = new ExpressionParser(new[] { prm }, selector, new object[] { }, ParsingConfig.Default);
var expr1 = parser.Parse(null);
WriteLine(
    ((MethodCallExpression)expr1).Method.DeclaringType
);

prints out:

System.Object
System.Nullable`1[System.Int32]

where both should have been the same.

zspitz avatar Mar 22 '22 22:03 zspitz

yes

jogibear9988 avatar Mar 23 '22 18:03 jogibear9988

@jogibear9988 and @zspitz

I did try to find the specific changes in source code in (https://github.com/zzzprojects/System.Linq.Dynamic/blob/archived/Src/System.Linq.Dynamic/DynamicLinq.cs) and this library.

But finding a method and getting the base-type is done the same way.

And the reason System.Nullable`1[System.Int32] is returned in that example code, is because this code line: image

And this is required.


So can you please provide some more details on why / how this should be fixed in this project?

StefH avatar Apr 17 '22 19:04 StefH

Hello @jogibear9988,

Can you please check my last comment?

StefH avatar Sep 09 '22 05:09 StefH

I think FindMethod should not return the Method it found, but the result of ".GetBaseDefinition()" of the Method it found. So you always return the MethodInfo TopMost in the Type hierarchy wich has it's own implementation.

jogibear9988 avatar Sep 10 '22 08:09 jogibear9988

see pull #630

jogibear9988 avatar Sep 12 '22 08:09 jogibear9988