dynamicexpresso / DynamicExpresso

C# expressions interpreter
http://dynamic-expresso.azurewebsites.net/
MIT License
2.02k stars 379 forks source link

NoApplicableMethodException for nullable variables given as parameters #309

Closed obones closed 5 months ago

obones commented 5 months ago

Hello,

I have the following code:

var interpreter = new Interpreter().EnableAssignment(AssignmentOperators.None);
const string formula = "Math.Min(var1, var2)";

foreach (var variable in variables)
    interpreter.SetVariable(variable.Name, variable.Value);

return interpreter.Eval<double>(formula);

where variables is a list of objects with Value declared as double?

When I run this, a NoApplicableMethodException is thrown with this message: No applicable method 'Min' exists in type 'Math'

If I do the same code in pure c#, I do get a warning about not checking for nullness but it runs just fine when the value is not null.

Shouldn't DynamicExpresso do the same and only raise if the value is null?

Right now, I have worked around by using this:

interpreter.SetVariable(variable.Name, variable.Value.GetValueOrDefault(double.NaN));

But it would be good if this was handled transparently.

metoule commented 5 months ago

Can you please clarify how you build variables? This code doesn't compile:

double? d1 = null;
double? d2 = null;
var d3 = Math.Min(d1, d2);

image

obones commented 5 months ago

Here is variables:

public class Variable
{
    public string Name { get; set; }
    public double? Value { get; set; }
}

var variables = new List<Variable>();

As to the code, I was convinced that it was automatically upgrading double? to double as needed, but that was in another location where there weren't any overloads for the method.

With overloads, this does not seem to happen and you are right, it errors out:

https://dotnetfiddle.net/ucLEd2

Sorry about the noise.

metoule commented 5 months ago

No worries, please let us know if you find an issue :)