0

I have problem. I can't find mechanism in .Net which allow me compile code in Windows form. I want have 1 textbox with code and later compiled code show in another box. How I can do this?

  • What do you mean by showing the compiled code? [Compiling C# code on runtime](https://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments) is easy. But it's unclear what do you mean by the compiled code, the array bytes of the generated assembly? The IL? Try Sharplab.io, play with the Results dropdown, any of them fit your requirement? – Martheen Apr 09 '20 at 09:40

2 Answers2

0

It sounds like you want to use a C# compiler from within your Windows Forms app, but I'm unsure what your other box would show.

If you're looking for just compiling and visually displaying IL, there are certainly ways to call Roslyn from Windows Forms.

If you're looking to dynamically generate a GUI, your options are a little less clear. I would consider exposing your own wrapper functions to another language. I would consider using Moonsharp to compile Lua code on the fly. IronPython would also work. I'm unfamiliar with whether F# language services could be invoked in a similar way, but these are options I'd consider.

If you're specifically looking to compile C# and use the results to display a WinForms GUI, you'll need to use CodeDOM. CodeDOM is a pretty deep rabbit hole even if it's powerful, and it won't be easy to sandbox any GUI it renders to the output container you have in mind.

lmcdo
  • 45
  • 8
0

As has been mentioned, compiling code using Roslyn is certainly the way forward. If you wish to see some output by executing the compiled code you may wish to create an abstract class for script writing which provides an entry point and a way of reporting output. You could then compile the script into a dll and use reflection to load the output assembly, instantiate an instance of your class (a class that implements ScriptTemplate below) and execute via the entry point.

abstract class ScriptTemplate
{
   public abstract void Main();

   public string Output
   {
      get;
      protected set;
   }

}

Your form could then write the Output property to a text box for example.

class Script : ScriptTemplate
{
   public override void Main()
   {
      Output = "Hello world!";
   }
}
tmren
  • 23
  • 6