0

Is it possble to compile a string into code without having to compile an entire new class?

Ive seen lots of tutorials and I have watched the documentations of the CodeDom framework, but in all of those it creates a new class and everything, what I want is to just compile 1 line and add it into the original code f.e.

string code = "5 + 1";

How can I compile that and at runtime use it like something like this:

double number = CompileAndCall("5 + 1");

CompileAndCall() should in some way convert the code to this:

return (double)5 + 1;

This should return the result ((double)6) from the method and store it in the number variable.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Arbitur
  • 38,684
  • 22
  • 91
  • 128
  • Like I said in the question, I want to alter code and while runtime. – Arbitur Apr 19 '14 at 19:54
  • As in original code I mean the code I compile and have in a text file in Visual Studios made by Microsoft. I dont know if CodeDom is the right approach, which is a one of the reasons why I made this question. Im pretty new to csharp and .Net and programming Microsoft stuff so I do not know many frameworks. – Arbitur Apr 19 '14 at 20:00
  • Exactly thats how I want it to work, like return. – Arbitur Apr 19 '14 at 20:02
  • Where does your `5 + 1` input come from? Can't you input `return 5 + 1;`? Does the output always have to be a double? – CodeCaster Apr 19 '14 at 20:08
  • It is possible but it's too complicated for a beginner. Learn to use C# properly. learn about how .net works then try to to implement eval in c#. There are a number of ways of generating code on the fly and strings might not be the best fit for your purpose. – MikeSW Apr 19 '14 at 20:16
  • 1
    Microsoft Roslyn does exactly this. You can have a look at my answer here: http://stackoverflow.com/a/13321964/389966 – Adi Lester Apr 19 '14 at 22:19
  • @AdiLester The old CTPs did. The scripting API was removed from the newest preview while it's being redesigned. – svick Apr 20 '14 at 11:35

0 Answers0