Class: `CSharpCompiler`
Provides functionality to compile C# code dynamically at runtime.
Summary
The CSharpCompiler class allows you to take C# source code as a string, compile it into an assembly, and then execute or use the compiled code within your application. This is particularly useful for scenarios like scripting, plugin architectures, or creating dynamic code evaluation tools.
Fields
This class does not contain any public fields.
Methods
CompileAssembly(string sourceCode, IEnumerable<string> referencedAssemblies)
public static Assembly CompileAssembly(string sourceCode, IEnumerable<string> referencedAssemblies)
Compiles the provided C# source code into an in-memory Assembly object.
Parameters
string sourceCode: The C# source code to compile.IEnumerable<string> referencedAssemblies: A collection of assembly names (e.g., "System.dll", "System.Core.dll") that the source code depends on.
Returns
- An
Assemblyobject representing the compiled code.
Example
using System;
using System.Reflection;
using System.Linq;
using Microsoft.CSharp; // Assuming this class is in Microsoft.CSharp
// ...
string code = @"
public class MyDynamicClass
{
public string Greet(string name)
{
return $""Hello, {name}!"";
}
}";
try
{
Assembly compiled = CSharpCompiler.CompileAssembly(code, new[] { "System.dll" });
Type dynamicType = compiled.GetType("MyDynamicClass");
object instance = Activator.CreateInstance(dynamicType);
MethodInfo greetMethod = dynamicType.GetMethod("Greet");
string result = (string)greetMethod.Invoke(instance, new object[] { "World" });
Console.WriteLine(result); // Output: Hello, World!
}
catch (Exception ex)
{
Console.WriteLine($"Compilation or execution error: {ex.Message}");
}
CompileToStream(string sourceCode, IEnumerable<string> referencedAssemblies, Stream outputStream)
public static void CompileToStream(string sourceCode, IEnumerable<string> referencedAssemblies, Stream outputStream)
Compiles the provided C# source code and writes the resulting assembly to the specified stream.
Parameters
string sourceCode: The C# source code to compile.IEnumerable<string> referencedAssemblies: A collection of assembly names that the source code depends on.Stream outputStream: The stream to write the compiled assembly to.
Returns
void
CompileToFile(string sourceCode, IEnumerable<string> referencedAssemblies, string outputPath)
public static void CompileToFile(string sourceCode, IEnumerable<string> referencedAssemblies, string outputPath)
Compiles the provided C# source code and saves the resulting assembly to a file.
Parameters
string sourceCode: The C# source code to compile.IEnumerable<string> referencedAssemblies: A collection of assembly names that the source code depends on.string outputPath: The full path to save the compiled assembly file (e.g., "MyDynamicAssembly.dll").
Returns
void