operator overloading

Oct 1, 2013 at 10:31 PM
Edited Oct 1, 2013 at 10:42 PM
Hi,

I would like to add multiple objects by using operator overloading.
Could you please help me how to proceed - the current solution is not working...
public class TS
{
        public int _value;

        public TS()
        {
        }
        
        public TS(int Value)
        {
            _value = Value;
        }

        public static TS operator +(TS a, TS b)
        {
            TS t = new TS();
            t._value = a._value + b._value;
            return t;
        }    
    }

      engine.AllowReflection = true;
      engine.AddHostType("Console", typeof(Console));
      engine.AddHostType("TS", typeof(TS));
      engine.Execute(@" t3 = new TS(15); 
       t4 = new TS(25);
       t5=t3+t4; ");
      engine.Execute("Console.WriteLine(t5)");
Coordinator
Oct 2, 2013 at 2:33 AM
Hello!

Unfortunately JavaScript doesn't support operator overloading. It supports custom conversion of objects to primitive values via valueOf(), but its operators require primitive operands and produce only primitive results.

However you can always let the host help out:
public static class TSUtil
{
    public static TS plus(this TS a, TS b)
    {
        return a + b;
    }
}
and then:
engine.AddHostType("TS", typeof(TS));
engine.AddHostType("TSUtil", typeof(TSUtil));
engine.Execute(@"
    t3 = new TS(15);
    t4 = new TS(25);
    t5 = t3.plus(t4);
");
Good luck!