Skip to content

Instantly share code, notes, and snippets.

@GReturn
Last active August 10, 2021 07:10
Show Gist options
  • Save GReturn/4a0feb0940c4926bc56898e53fffb239 to your computer and use it in GitHub Desktop.
Save GReturn/4a0feb0940c4926bc56898e53fffb239 to your computer and use it in GitHub Desktop.
C# - Evaluate a mathematical expression as a string
/*
An implementation of the Evaluate() function,
similar to other programming languages,
wherein it evaluates string as an expression.
Taken from https://stackoverflow.com/a/6052679/14139842
NOTE: Given that the source is from 2011,
there is a possibility that C# already has this function.
*/
public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment