Skip to content

Commit

Permalink
Fix user defined operator resolution when the operator is defined on …
Browse files Browse the repository at this point in the history
…the right operand's type.
  • Loading branch information
metoule committed May 10, 2021
1 parent 836976d commit ef71cf8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/DynamicExpresso.Core/Parsing/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1937,6 +1937,10 @@ private MethodData FindBinaryOperator(string operatorName, Expression left, Expr
// we found a matching user defined operator on either type, but it might be the same method
if (userDefinedOperator != null && rightOperator != null && !ReferenceEquals(userDefinedOperator.MethodBase, rightOperator.MethodBase))
throw error;

// we didn't find an operator on the left type, but we found one on the right type
if (userDefinedOperator == null && rightOperator != null)
userDefinedOperator = rightOperator;
}

return userDefinedOperator;
Expand Down
17 changes: 17 additions & 0 deletions test/DynamicExpresso.UnitTest/OperatorsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,16 @@ public ClassWithOverloadedBinaryOperators(int value)
return new ClassWithOverloadedBinaryOperators(-instance._value);
}

public static ClassWithOverloadedBinaryOperators operator *(ClassWithOverloadedBinaryOperators left, int right)
{
return new ClassWithOverloadedBinaryOperators(left._value * right);
}

public static ClassWithOverloadedBinaryOperators operator *(int left, ClassWithOverloadedBinaryOperators right)
{
return new ClassWithOverloadedBinaryOperators(left * right._value);
}

public override bool Equals(object obj)
{
if (obj == null)
Expand Down Expand Up @@ -613,6 +623,13 @@ public void Can_use_overloaded_operators_on_derived_class()
var z = new DerivedClassWithOverloadedBinaryOperators(10);
Assert.IsTrue((x + z) == "13");
Assert.IsTrue(target.Eval<bool>("(x + z) == \"13\"", new Parameter("z", z)));

Assert.IsTrue((x * 4) == "12");
Assert.IsTrue(target.Eval<bool>("(x * 4) == \"12\""));

// ensure a user defined operator can be found if it's on the right side operand's type
Assert.IsTrue((4 * x) == "12");
Assert.IsTrue(target.Eval<bool>("(4 * x) == \"12\""));
}

[Test]
Expand Down

0 comments on commit ef71cf8

Please sign in to comment.