26

I want some code that compiles the code that is in my TextBox (for example). What I mean is I want to compile code after running the program. How can I do this?

0

2 Answers 2

21

See this article:

http://support.microsoft.com/kb/304655

Here's the sample code they provide:

var codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

var parameters = new CompilerParameters()
{
    GenerateExecutable = true,
    OutputAssembly = Output,
};
CompilerResults results = icc.CompileAssemblyFromSource(parameters, sourceString);

if (results.Errors.Count > 0)
{
    foreach(CompilerError error in results.Errors)
    {
        textBox2.Text = textBox2.Text
            + "Line number " + error.Line
            + ", Error Number: " + error.ErrorNumber
            + ", '" + error.ErrorText + ";"
            + Environment.NewLine + Environment.NewLine
            ;
    }
}

As Aliostad has mentioned in his answer, be careful with this solution, though. You will need to make sure your compiled code ends up in its own AppDomain, otherwise you will experience memory leaks.

See this related question on how to load the code into a separate AppDomain:

How can I prevent CompileAssemblyFromSource from leaking memory?

Sign up to request clarification or add additional context in comments.

1 Comment

BTW this code sample is only minimally edited. I'd personally use a StringBuilder on that error message loop, and overwrite the text box's text rather than appending to it.
17

See here and here.

Just be careful, any code that is compiled and loaded, cannot be unloaded. This can cause memory leak, i.e. if someone keeps typing and changing the code and compiling it, assemblies get loaded and you will ultimately run out of memory.

One solution is to create a second AppDomain and load the assembly in there and when not needed, unload the AppDomain.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.