Question Can I execute C# code in C#?

csharp

Member
Joined
May 3, 2021
Messages
11
Programming Experience
Beginner
Can I execute C# code in C#? I've the variable:
C#:
string csharpCode = @"
using System;
class Program {
           static void Main() {
                        Console.WriteLine(""Hello world"");
           }
}

"

and I want execute it, is there a function for do this?
 
Last edited by a moderator:
Yes. That's how the standard C# compiler works. Multiple source files get compiled into a single assembly.

The difference between the single executable described above and the standard compiled .NET assembly is that the former packs not just the main running assembly, but also all the dependent assemblies into a single file. The latter will only be an assembly that contains all the code that you compiled -- any dependent assemblies will either be in the same directory as the main executable or installed in the GAC.
 
Sorry but I haven't understood how can I compile the project in a single file and execute it with System.Reflection.Assembly.LoadFile()?
 
Right click on your project in the solution explorer. Select "Build". Visual Studio will compile all the .CS files in your project into a single assembly.
 
If you don't even understand the fundamentals of how your basic developer tools works, why are you taking on this more complex problem? I would recommend stepping back and learning more about the language and the tools surrounding the language before embarking on reflection and executing other code.
 
Back
Top Bottom