Hello, is it possible to make a string, for example, string text="if(a>0) {a+b}"; The program is understood as a simple code. Is there any API for this?
- oneI bet you don't really need this. Tell us what a real problem you are solving. - VladD
- @TigranVoskanyan, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky ♦
- there is a CSharpCodeProvider, an example here - Stack
1 answer
As such, in the language there is no such possibility - it is unsafe and, in general, not necessary. If you let the user execute arbitrary code entered in the form of a normal string, this can lead to various non-pleasant and undesirable consequences. However, the C # developers are not sawing a project called Roslyn for the first day (you can read a few words about it here and here ). This project will allow you to access the compiler and allow you to perform tasks like yours. In addition, there are open source solutions, for example , this project. A small example from the page of this project:
var interpreter = new Interpreter(); var result = interpreter.Eval("8 / 2 + 2"); I think what you need. If you wish, you can write your own bike - within the institute's programming courses there are a number of disciplines dedicated to this. However, if it is not done through one place, then this is a rather laborious, though interesting, process that requires studying a rather extensive spectrum of literature.