CodeDomProvider Class

Namespace: System.CodeDom.Compiler
Assembly: System.dll

Summary

Provides an abstract base class for implementing a code compiler. CodeDOM (Code Document Object Model) is a set of .NET classes that represent source code, enabling developers to programmatically generate and compile code.

The CodeDomProvider class is the entry point for working with code generation and compilation using CodeDOM. Derived classes provide implementations for specific programming languages (e.g., C#, Visual Basic).

Public Constructors

Public Methods

Protected Methods

Remarks

To use CodeDomProvider, you typically need to obtain an instance of a concrete implementation for a specific language. For example, you can use the Microsoft.CSharp.CSharpCodeProvider for C# or Microsoft.VisualBasic.VBCodeProvider for Visual Basic.

The CompilerParameters class is used to specify settings for the compilation process, such as output assembly name, referenced assemblies, and optimization flags.


using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp.CSharpCodeProvider; // For C#

public class CompilerExample
{
    public static void Main(string[] args)
    {
        // Create a C# code provider
        using (CodeDomProvider provider = new CSharpCodeProvider())
        {
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = true;
            cp.OutputAssembly = "MyDynamicAssembly.exe";
            cp.ReferencedAssemblies.Add("System.dll");

            string sourceCode = @"
                using System;

                public class HelloWorld
                {
                    public static void Main()
                    {
                        Console.WriteLine(""Hello from dynamic code!"");
                    }
                }";

            CompilerResults results = provider.CompileAssemblyFromSource(cp, 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("Assembly compiled successfully!");
                // You can now load and execute MyDynamicAssembly.exe
            }
        }
    }
}
            

See Also