Executing a string in C# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Executing a string in C#

Hello there! I am working on a project and I want to execute a C# statement which in inside a string. For example: string s = "int a = 2"; some_cool_method(s); Console.WriteLine(a); //This should print 2 in the console. How do I do that? You can suggest me any way. (Including managed code (APIs) and unmanaged code). Thank You.

26th Sep 2018, 4:14 PM
Shreyas Sable
Shreyas Sable - avatar
1 Answer
+ 1
You might get some ideas here, but a quick read implies to me that there isn't an eval-in-place option, only eval-and-assign-result (to local var). https://stackoverflow.com/questions/1024070/c-sharp-eval-support ...mentions "DataBinder.Eval from System.Web.UI" and a project named "Dynamic Expresso" Compilation and Reflection come up as alternative hints.
26th Sep 2018, 4:30 PM
Kirk Schafer
Kirk Schafer - avatar