mparlak / Flee

Fast Lightweight Expression Evaluator
628 stars 120 forks source link

Overloading 'AND' and 'OR' Operator in C# gives an Exception #54

Open Peter4Git opened 5 years ago

Peter4Git commented 5 years ago

I treid to overload the 'And' Operator in MyClass (C#). Flee gives me the following Exception:

"AndOrElement: Operation 'And' is not defined for types 'MyClass' and 'MyClass'"

Overloading the '+' and'-' Operator works well.

how can I overload the 'AND' 'OR' Operators in an C# Class ?

class Program
{
    static void Main(string[] args)
    {
        ExpressionContext context = new ExpressionContext();
        VariableCollection variables = context.Variables;

        variables.Add("a", new MyClass("1"));
        variables.Add("b", new MyClass("2"));

        try
        {
            Console.WriteLine( context.CompileDynamic("a + b").Evaluate() ); // works well 
            Console.WriteLine( context.CompileDynamic("a - b").Evaluate() ); // this too

            // following gives me an exception:
            // "AndOrElement: Operation 'And' is not defined for types 'MyClass' and 'MyClass'" 
            Console.WriteLine(context.CompileDynamic("a and b").Evaluate()); 
            Console.WriteLine(context.CompileDynamic("a or b").Evaluate()  );
        }

        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }
}

public class MyClass
{
    private string value;

    public MyClass(String v)
    {
        value = v;
    }

    public bool ToBool()
    {
        if (value == "0") return false;
        if (value == "") return false;
        return true;
    }

    public int ToInt()
    {
        return Convert.ToInt32(value);
    }

    public static bool operator &(MyClass c1, MyClass c2)
    {
        return c1.ToBool() && c2.ToBool();
    }

    public static bool operator |(MyClass c2, MyClass c1)
    {
        return c1.ToBool() || c2.ToBool();
    }

    public static int operator +(MyClass c2, MyClass c1)
    {
        return c1.ToInt() + c2.ToInt();
    }

    public static int operator -(MyClass c2, MyClass c1)
    {
        return c1.ToInt() - c2.ToInt();
    }
}
Doc-Saintly commented 5 years ago

I could also use an answer for this. I guess it is because of the same reason: I need to use Excel-like syntax. or(true,false) instead of true or false

hunkydoryrepair commented 3 years ago

I believe somebody has added support for overloading AND/OR and there is an active pull request on it.