I would like to have expression classes that compare two objects and pass the below test.
public abstract class ComparisonExpression
{
public bool Evaluate(IComparable left, object right)
{
if (left == null && right == null)
return true;
if (left == null || right == null)
return false;
return GetResult(left.CompareTo(right));
}
protected abstract bool GetResult(int comparisonResult);
}
public class AreEqualExpression : ComparisonExpression
{
protected override bool GetResult(int comparisonResult)
{
return comparisonResult == 0;
}
}
// TEST
const int i = 123;
const long l = 123L;
const string s = "123";
Assert.IsTrue(new AreEqualExpression().Evaluate(i, l));
Assert.IsFalse(new AreEqualExpression().Evaluate(i, s));
Assert.IsFalse(new AreEqualExpression().Evaluate(l, s));
It seems like IComparable implementation expects the given type matches the current type. I am having an exception like "Object must be of type Int32.".
I thought returning false if types are not equal. It prevents the exception but it brakes the behavior that i want.
Also I thought about a type conversion but this time string and int comparison will return true, which i do not want.
Any suggestions?