P
P
pavviaz2018-10-04 22:31:04
C++ / C#
pavviaz, 2018-10-04 22:31:04

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;
        }

It is logical that the compiler will simplify the variable k, and the function will return the number 9.
With this code, I will get an error:
public int Try()
        {
            string q = "3*3";
            return Convert.ToInt32(q);
        }

And how can you convert a string to an Int with automatic compiler simplification, and end up with 9 in the function described above?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eRKa, 2018-10-04
@pavviaz

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

B
basrach, 2018-10-06
@basrach

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 question

Ask a Question

731 491 924 answers to any question