I'm have to calculate string input using NCalc, but I would like to save it (result) as a string. How do I do that?
Expression expressionEv = new Expression(expressionProccessed);
string value = expressionEv.Evaluate ();
Following code returns error:
Error CS0266: Cannot implicitly convert type `object' to `string'. An explicit conversion exists (are you missing a cast?)
Is there any way to convert it to string? Or maybe other way? Thanks in advance! ;)
Your error message tells you almost everything you need to know:
Lets look at this in parts.
1.
This part is telling you that the call to expressionEv.Evaluate(); is returning a something that has the type 'object', not string. You cannot assign types to other types.
2.
This part is telling you that you are attempting to convert the object to a string, and while it is possible, you haven't told the compiler how you want to do it. It even suggest a solution: "(are you missing a cast?)"
There are 2 ways to do it:
Explicitly cast:
string value = (string)expressionEv.Evaluate();
Call the ToString() method that all objects have (inherited from the base object class):
string value = expressionEv.Evaluate().ToString();
I would suggest you use the ToString method. The explicit cast runs a risk of throwing an exception if the type isn't ultimately a string.