Answer the question
In order to leave comments, you need to log in
How can one write a String to an Int with auto simplification?
Hello
, I have a piece of code:
public int Try()
{
k = 3*3;
return k;
}
public int Try()
{
string q = "3*3";
return Convert.ToInt32(q);
}
Answer the question
In order to leave comments, you need to log in
The Convert.ToInt32(string) method converts a string value to its equivalent integer. This method does not parse your expression to build an expression tree from your string, and certainly does not attempt to evaluate the final value.
Everything is allowed. But for this you need to either implement such functionality yourself, or find a ready-made implementation in the open spaces. There is no such native method in C#.
If what the user enters corresponds to the grammar of the C# language, then install the nuget package Microsoft.CodeAnalysis.Scripting and then simply:
var userInput = "3*3";
var result = await CSharpScript.EvaluateAsync<int>(userInput);
Console.WriteLine(result); // 9
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question