Create Class object from string containing source code

465 views Asked by At

I'm creating a C# application in which code is compiled at runtime, the code is contained in a string (and the string gets its value from a ScintillaNET Control, it just returns text, the string with code is working as intended).

My question is: is there a way to make some sort of Class-object from this source code at runtime? For example, the string contains this value:

namespace _Testing {

class Program {
    static void Main(string[] args) {
        Console.Title = "Program";
        Console.WriteLine("If you can read this, it's all good!");
        Console.ReadKey();
    }
  }
}

This code is being compiled by my CSharpCodeProvider compiler at runtime (with a CompileAssemblyFromSourceBatch - because I'm passing an array of classes to be compiled). However, I want to be able to set the MainClass property of the compiler at runtime, and that requires getting the namespace out of the classes.

So I was thinking of creating some sort of object of each class-source code string which will make me able to achieve my goal. Any other ideas are of course welcome too.

1

There are 1 answers

1
BendEg On

What you want is not the CSharpCodeProver, for compiling and loading dynamic code. In your case i would recommend to use the DLR (not the CLR) from the .Net Framework.

Or you can take a look at .NET-Compiler-Plattform

What you try will not work.