sebastienros / fluid

Fluid is an open-source .NET template engine based on the Liquid template language.
MIT License
1.43k stars 178 forks source link

The == operator only compares the reference #661

Open Yaming-Hub opened 5 months ago

Yaming-Hub commented 5 months ago

The default == and != operator compare equality by reference. So when I have classes overrides Equals() method, these customized equal logic won't be honored. The same issue also impacts contains binary operator. Ideally when compare objects or check if an array contains an object, we should compare value instead of reference.

Yaming-Hub commented 5 months ago

Right now I work around this problem by defining my own ValueEqualBinaryExpression class and overwrite the "==" operator in parser.

    public sealed class ValueEqualBinaryExpression : BinaryExpressionBase
    {
        public ValueEqualBinaryExpression(Expression left, Expression right) : base(left, right)
        {
        }

        protected override FluidValue Evaluate(FluidValue leftValue, FluidValue rightValue, TemplateContext context)
        {            
            if (leftValue.Type == FluidValues.Object && rightValue.Type == FluidValues.Object)
            {
                var left = leftValue.ToObjectValue();
                var right = rightValue.ToObjectValue();
                return left.Equals(right)
                    ? BooleanValue.True
                    : BooleanValue.False;
            }

            return leftValue.Equals(rightValue) 
                ? BooleanValue.True
                : BooleanValue.False;
        }
    }