Namespace: System.Runtime.Compilation
Description
Provides types that enable the dynamic compilation of code at run time. This namespace is part of the .NET Framework and is used for scenarios requiring on-the-fly code generation and execution.
Key types in this namespace facilitate the creation of assemblies, the compilation of source code strings into executable code, and the execution of that compiled code within the current application domain.
Classes
-
Compiler
Represents a compiler that can be used to compile code.
-
CompilerParameters
Contains the parameters for a compilation.
-
CompilerResults
Contains the results of a compilation.
-
CodeDomProvider
Abstract base class that provides a way to access the functionality of a code generation and code compilation tool.
Interfaces
-
ICompiler
Defines methods for a compiler.
Enumerations
-
CompilerErrorLevel
Specifies the level of detail for compiler errors.
Usage Example
using System;
using System.CodeDom.Compiler;
using System.Reflection;
public class DynamicCompilationExample
{
public static void Main(string[] args)
{
string sourceCode = @"
using System;
public class Greeter
{
public string SayHello(string name)
{
return $""Hello, {name}!"";
}
}
";
// Get a CodeDomProvider for C#
using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"))
{
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false; // Don't generate an executable
parameters.GenerateInMemory = true; // Compile in memory
// Add necessary assemblies
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
// Compile the source code
CompilerResults results = provider.CompileAssemblyFromSource(parameters, sourceCode);
if (results.Errors.HasErrors)
{
Console.WriteLine("Compilation errors:");
foreach (CompilerError error in results.Errors)
{
Console.WriteLine($" {error.ErrorNumber}: {error.ErrorText} (Line {error.Line})");
}
}
else
{
Console.WriteLine("Compilation successful!");
// Get the compiled assembly
Assembly assembly = results.CompiledAssembly;
// Create an instance of the Greeter class
object greeterInstance = assembly.CreateInstance("Greeter");
// Get the SayHello method
MethodInfo sayHelloMethod = greeterInstance.GetType().GetMethod("SayHello");
// Invoke the method
string message = (string)sayHelloMethod.Invoke(greeterInstance, new object[] { "World" });
Console.WriteLine(message); // Output: Hello, World!
}
}
}
}