Convert NCalc expression to string

1.4k Views Asked by At

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! ;)

2

There are 2 best solutions below

0
On BEST ANSWER

Your error message tells you almost everything you need to know:

Error CS0266: Cannot implicitly convert type `object' to `string'. An explicit conversion exists (are you missing a cast?)

Lets look at this in parts.

1.

`Cannot implicitly convert type `object' to `string'.`

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.

An explicit conversion exists (are you missing a cast?)

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:

  1. Explicitly cast:

    string value = (string)expressionEv.Evaluate();

  2. 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.

0
On

According to the documentation Evaluate returns an object, so you need to explicitly cast it to a string.

string value = (string)expressionEv.Evaluate();

Or call ToString():

string value = expressionEv.Evaluate().ToString();

Note that Evaluate can also throw an exception, so casting might fail.