Convert a String Into an Expression

Hello, I have a challenging task of converting strings into executable expressions.

string MyCalc = “100+200”;
decimal result = HopefulNamespace.ExecuteExpression(MyCalc);

As you can see, I’m hopeful for something in the library that has a method that converts strings into executable expressions. Has anyone been down this road before? How would you attack this? I could create a method of my own, but it seems to me like it would make sense that something already exists.

Are the strings always formatted in a consistent way?

1 Like

From what I’ve researched so far, they will have to be. A lot of string manipulation will happen before I finally need them converted.

Give this thread a look over. Lots of solutions with downsides of there own. Quickest solution would be using the DataTable.Compute() method

2 Likes

Word of warning on functions like eval() … they impose HUGE security risks.

1 Like

Might I ask where this string is coming from, and why it’s not being stored as its preferred data types? I’d think even if it’s coming from an external application, we might be able to parse it out prior to storing it as a string.

2 Likes

I appreciate all the feedback!!! I found, and was able to get the DataTable.Compute method working for me shortly after posting. Using:

System.Text
System.Linq.Expressions

I was able to convert strings into usable expression results in Epicor. The challenge will be “cleaning” and manipulating the strings that will be entered in. It will have to be quite rigid as far as user-entry. String-Fun coming my way! ← not sarcastic, I enjoy this stuff :slight_smile:

In its most simplistic/experimental form (to help those in the future):

private void btnCalc_Click(object sender, System.EventArgs args)
{		
	string OrigCalc = "A+B";
	string QueryForA = "100";
	string QueryForB = "200";
	StringBuilder sb = new StringBuilder(OrigCalc);
	sb.Replace("A", QueryForA);
	sb.Replace("B",QueryForB);

	decimal result = Convert.ToDecimal(new DataTable().Compute(sb.ToString(), null));

	System.Data.DataRow edvUD07Row = edvUD07.CurrentDataRow;
	edvUD07Row.BeginEdit();
	edvUD07.dataView[edvUD07.Row]["Number01"] = result;
	edvUD07Row.EndEdit();
}
1 Like

That’s intriguing: “stored as preferred data types” and I think that’s something I will look into. Thank you for the input. I just thought it simpler to convert the calculation into a string and then chop it up before pushing it through as a calculation. The problem is, the calculation entry screen will have things like MyVariable1+MyVariable2. When the calculation is used elsewhere, I’m going to have to use MyVariable# and replace the variable-name with the actual number entered in, and then compute them.

That stackoverflow thread mentions issues with memory leaks. Is the DataTable created in the .ToDecimal() function properly disposed of?

1 Like

Excellent point! I will be sure to clean it up in my final result.