When overloading some operators ...
class Expression { string exprStr; public static explicit operator Expression(int value) { return new Expression() { exprStr = value.ToString() }; } public static Expression operator *(Expression exp, int value) { return new Expression() { exprStr = exp.exprStr + " * " + value.ToString() }; } public override string ToString() { return exprStr; } } class Program { static void Main() { int iTwo = 2; string theString = ((Expression)iTwo * iTwo).ToString(); } }
You, of course, will need to overload the other operators that you need in the same way (e.g. +
, /
, etc.).
You should also provide methods that accept types other than int if you need them, but the basic idea remains the same.
Please note that you should only give the first operand to Expression, otherwise you will only get the result for the conversion.
source share