0

I am trying to make something like a command line for a game that I am developing using C#. I would like to have something like:

string code;
code = Console.ReadLine();
Something.RunCode(code);

Where I can input a C# code snippet that interacts with things happening to the current thread of execution in my program (for example if I'm stuck in an infinite loop in the main program I can pull up the command line in a separate thread and type in "break;" or "MainThread.Abort();" and I can get out). I want to be able to use C# command line to interact with my program while it it running. I don't know if this is even possible, but I think it will really help me with debugging and such (like use the command line to make a part of my program throw an error and see how it handles it, without having to stop the program, add the error into the source code, and re-build). Thank you in advance.

vasilescur
  • 240
  • 2
  • 5
  • 16
  • Can you give example of code variable content? – Krzysztof Madej Feb 07 '14 at 15:57
  • 2
    You may take a look at http://stackoverflow.com/questions/7944036/compile-c-sharp-code-in-the-application – Max Markov Feb 07 '14 at 15:57
  • C# code is a [compiled language](http://en.wikipedia.org/wiki/Compiled_language). It cannot just be run, like javascript wich is an [Interpreted language](http://en.wikipedia.org/wiki/Interpreted_language). So you need to compile this into something runnable before you can let it do anything – Liam Feb 07 '14 at 15:58
  • also this is seriously dangerous. – Liam Feb 07 '14 at 15:58
  • There's also [scriptcs](http://scriptcs.net/), which is very much like what you describe: A proper C# REPL. – Magus Feb 07 '14 at 16:03
  • Check out my answer here http://stackoverflow.com/questions/12278251/dynamically-changing-conditions-of-an-if-statement-in-c-sharp/18854045#18854045 – reggaeguitar Feb 07 '14 at 16:10
  • Thank you all for the great responses. I am not concerned about the safety of the code, as I am the only one who will be using it. – vasilescur Feb 07 '14 at 16:40

2 Answers2

0

You can compile an assembly on the fly

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library";

compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;

compilerParams.OutputAssembly = outTempPath;

CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourceCode);

You should sandbox the execution though for safety reasons.

Also, read this interesting article.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Take a look at project Roslyn. Specialy the Scripting document should set you on your way.

The code is bit too large to include here.

GvS
  • 52,015
  • 16
  • 101
  • 139