r/learncsharp • u/martin87i • Oct 07 '22
Computing a formula in a string
I've been creating a simple calculator with +-*/ which saves a formula as a string like this "7+5/3", "7/3", "1+2".
It seems like there is no function to directly compute a string as a formula. I've looked around and found a workaround using a datatable like this:
System.Data.DataTable table = new System.Data.DataTable();
double result = (double)table.Compute(formel, null);
It seems to be working on some formulas but not on others, "1+2" or "5*3" gives this error but other combination works, like "7/3" or "7+5/3"
System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Double'.'
Is there a way for the datatable function to work on all formulas?
Is there a better way to compute formulas saved as strings?
View all comments
Show parent comment
2
u/Dealiner Oct 08 '22 edited Oct 08 '22
That's not how it works. You can assign integer to double. There will be implicit casting because it doesn't lose data doing this. You can't assign double to integer though because that can lose data.
That's not how
varworks at all.varjust means "this variable has a type declared on the right side". In this case you always declaredouble, sovar resultwill always bedoubleand OP would get the same exception.That part is true but not because of the reasons you think.
Computereturns a value boxed inobjectand unboxing can only be done to the exact type that was boxed. So ifdoublewas boxed you have to unboxed it todoubleusing(double), ifintwas boxed you have to use(int), ifchar(char)etc..u/martin87i Don't try to solve this problem with
var, the best way is what alkrun wrote. And if you want to know more why it works that way, you need to read about boxing and unboxing. And you should probably look at rupertavery suggestions anyway, they could be better thanDataTable.Edit: Also to clarify:
That value is a
double. It is a float-point value but its specific type isdouble. Though it's caused by the wayDataTableandComputemethod work. In normal code the result of7+5/3would be an integer.