Export (0) Print
Expand All

CodeDomProvider Class

Provides a base class for CodeDomProvider implementations. This class is abstract.

Namespace: System.CodeDom.Compiler
Assembly: System (in system.dll)

public abstract class CodeDomProvider : Component
/** @attribute ComVisibleAttribute(true) */ 
public abstract class CodeDomProvider extends Component
public abstract class CodeDomProvider extends Component
Not applicable.

A CodeDomProvider can be used to create and retrieve instances of code generators and code compilers. Code generators can be used to generate code in a particular language, and code compilers can be used to compile code into assemblies.


In the Microsoft .NET Framework version 2.0, the methods made available in the code generator and code compiler are available directly from the code provider. You do not need to call CreateGenerator or CreateCompiler to access the methods, and those methods are marked as obsolete. This applies to preexisting as well as new code provider implementations.

A CodeDomProvider implementation typically provides code generation and/or code compilation interfaces for generating code and managing compilation for a single programming language. Several languages are supported by CodeDomProvider implementations that ship with the .NET Framework SDK. These languages include C#, Visual Basic, C++, J#, and JScript. Developers or compiler vendors can implement the ICodeGenerator and ICodeCompiler interfaces and provide a CodeDomProvider that extends CodeDom support to other programming languages.

The <system.codedom> Element in the machine configuration file (Machine.config) provides a mechanism for developers and compiler vendors to add configuration settings for additional CodeDomProvider implementations.

The CodeDomProvider class provides static methods to discover and enumerate the CodeDomProvider implementations on a computer. The GetAllCompilerInfo method returns the settings for all CodeDomProvider implementations on a computer. The GetCompilerInfo method returns the settings for a specific CodeDomProvider implementation, based on the programming language name. The CreateProvider method returns an instance of a CodeDomProvider implementation for a specific language.

For more details on language provider settings in the configuration file, see Compiler and Language Provider Settings Schema.


This class makes a link demand and an inheritance demand at the class level. A SecurityException is thrown if either the immediate caller or the derived class does not have full trust permission. For details about security demands, see Link Demands and Inheritance Demands.

Notes to Inheritors: In the .NET Framework versions 1.0 and 1.1, code providers consist of implementations of CodeDomProvider, ICodeGenerator, ICodeParser, and ICodeCompiler. In the .NET Framework 2.0, the CreateGenerator, CreateParser, and CreateCompiler methods are obsolete, and the methods of ICodeGenerator and ICodeCompiler are directly available in the CodeDomProvider class. You should override those methods in your code provider implementation and not call the base methods.

The following example program can generate and compile source code based on a CodeDOM model of a program that prints "Hello World" using the Console class. A Windows Forms user interface is provided. The user can select the target programming language from several selections: C#, Visual Basic, and JScript.

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.JScript;

// This example demonstrates building a Hello World program graph 
// using System.CodeDom elements. It calls code generator and
// code compiler methods to build the program using CSharp, VB, or
// JScript.  A Windows Forms interface is included. Note: Code
// must be compiled and linked with the Microsoft.JScript assembly. 
namespace CodeDOMExample
    class CodeDomExample
        // Build a Hello World program graph using 
        // System.CodeDom types.
        public static CodeCompileUnit BuildHelloWorldGraph()
            // Create a new CodeCompileUnit to contain 
            // the program graph.
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare a new namespace called Samples.
            CodeNamespace samples = new CodeNamespace("Samples");
            // Add the new namespace to the compile unit.

            // Add the new namespace import for the System namespace.
            samples.Imports.Add(new CodeNamespaceImport("System"));

            // Declare a new type called Class1.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
            // Add the new type to the namespace type collection.

            // Declare a new code entry point method.
            CodeEntryPointMethod start = new CodeEntryPointMethod();

            // Create a type reference for the System.Console class.
            CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");

            // Build a Console.WriteLine statement.
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine",
                new CodePrimitiveExpression("Hello World!"));

            // Add the WriteLine call to the statement collection.

            // Build another Console.WriteLine statement.
            CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine",
                new CodePrimitiveExpression("Press the Enter key to continue."));

            // Add the WriteLine call to the statement collection.

            // Build a call to System.Console.ReadLine.
            CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(
                csSystemConsoleType, "ReadLine");

            // Add the ReadLine statement.

            // Add the code entry point method to
            // the Members collection of the type.

            return compileUnit;

        public static void GenerateCode(CodeDomProvider provider,
            CodeCompileUnit compileunit)
            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
                sourceFile = "TestGraph" + provider.FileExtension;
                sourceFile = "TestGraph." + provider.FileExtension;

            // Create an IndentedTextWriter, constructed with
            // a StreamWriter to the source file.
            IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), "    ");
            // Generate source code using the code generator.
            provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
            // Close the output file.

        public static CompilerResults CompileCode(CodeDomProvider provider,
                                                  String sourceFile,
                                                  String exeFile)
            // Configure a CompilerParameters that links System.dll
            // and produces the specified executable file.
            String[] referenceAssemblies = { "System.dll" };
            CompilerParameters cp = new CompilerParameters(referenceAssemblies,
                                                           exeFile, false);
            // Generate an executable rather than a DLL file.
            cp.GenerateExecutable = true;

            // Invoke compilation.
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);
            // Return the results of compilation.
            return cr;

    public class CodeDomExampleForm : System.Windows.Forms.Form
        private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button compile_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox();
        private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox();
        private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label();

        private void generate_button_Click(object sender, System.EventArgs e)
            CodeDomProvider provider = GetCurrentProvider();
            CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph());

            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
                sourceFile = "TestGraph" + provider.FileExtension;
                sourceFile = "TestGraph." + provider.FileExtension;

            // Read in the generated source file and
            // display the source text.
            StreamReader sr = new StreamReader(sourceFile);
            textBox1.Text = sr.ReadToEnd();

        private void compile_button_Click(object sender, System.EventArgs e)
            CodeDomProvider provider = GetCurrentProvider();

            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
                sourceFile = "TestGraph" + provider.FileExtension;
                sourceFile = "TestGraph." + provider.FileExtension;

            // Compile the source file into an executable output file.
            CompilerResults cr = CodeDomExample.CompileCode(provider,

            if (cr.Errors.Count > 0)
                // Display compilation errors.
                textBox1.Text = "Errors encountered while building " +
                                sourceFile + " into " + cr.PathToAssembly + ": \r\n\n";
                foreach (CompilerError ce in cr.Errors)
                    textBox1.AppendText(ce.ToString() + "\r\n");
                run_button.Enabled = false;
                textBox1.Text = "Source " + sourceFile + " built into " +
                                cr.PathToAssembly + " with no errors.";
                run_button.Enabled = true;

        private void run_button_Click(object sender,
            System.EventArgs e)

        private CodeDomProvider GetCurrentProvider()
            CodeDomProvider provider;
            switch ((string)this.comboBox1.SelectedItem)
                case "CSharp":
                    provider = CodeDomProvider.CreateProvider("CSharp");
                case "Visual Basic":
                    provider = CodeDomProvider.CreateProvider("VisualBasic");
                case "JScript":
                    provider = CodeDomProvider.CreateProvider("JScript");
                    provider = CodeDomProvider.CreateProvider("CSharp");
            return provider;

        public CodeDomExampleForm()
            // Set properties for label1
            this.label1.Location = new System.Drawing.Point(395, 20);
            this.label1.Size = new Size(180, 22);
            this.label1.Text = "Select a programming language:";
            // Set properties for comboBox1
            this.comboBox1.Location = new System.Drawing.Point(560, 16);
            this.comboBox1.Size = new Size(190, 23);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Items.AddRange(new string[] { "CSharp", "Visual Basic", "JScript" });
            this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left
                                    | System.Windows.Forms.AnchorStyles.Right
                                    | System.Windows.Forms.AnchorStyles.Top;
            this.comboBox1.SelectedIndex = 0;
            // Set properties for generate_button. 
            this.generate_button.Location = new System.Drawing.Point(8, 16);
            this.generate_button.Name = "generate_button";
            this.generate_button.Size = new System.Drawing.Size(120, 23);
            this.generate_button.Text = "Generate Code";
            this.generate_button.Click += new System.EventHandler(this.generate_button_Click);
            // Set properties for compile_button.
            this.compile_button.Location = new System.Drawing.Point(136, 16);
            this.compile_button.Name = "compile_button";
            this.compile_button.Size = new System.Drawing.Size(120, 23);
            this.compile_button.Text = "Compile";
            this.compile_button.Click += new System.EventHandler(this.compile_button_Click);
            // Set properties for run_button.
            this.run_button.Enabled = false;
            this.run_button.Location = new System.Drawing.Point(264, 16);
            this.run_button.Name = "run_button";
            this.run_button.Size = new System.Drawing.Size(120, 23);
            this.run_button.Text = "Run";
            this.run_button.Click += new System.EventHandler(this.run_button_Click);
            // Set properties for textBox1.        
            this.textBox1.Anchor = (System.Windows.Forms.AnchorStyles.Top
                                     | System.Windows.Forms.AnchorStyles.Bottom
                                     | System.Windows.Forms.AnchorStyles.Left
                                     | System.Windows.Forms.AnchorStyles.Right);
            this.textBox1.Location = new System.Drawing.Point(8, 48);
            this.textBox1.Multiline = true;
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(744, 280);
            this.textBox1.Text = "";
            // Set properties for the CodeDomExampleForm.
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(768, 340);
            this.MinimumSize = new System.Drawing.Size(750, 340);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {this.textBox1, 
                this.run_button, this.compile_button, this.generate_button,
                this.comboBox1, this.label1 });
            this.Name = "CodeDomExampleForm";
            this.Text = "CodeDom Hello World Example";

        protected override void Dispose(bool disposing)

        static void Main()
            Application.Run(new CodeDomExampleForm());

  • SecurityAction.LinkDemand  for full trust for the immediate caller. This class cannot be used by partially trusted code.
  • SecurityAction.InheritanceDemand  for full trust for inheritors. This class cannot be inherited by partially trusted code.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

Community Additions

© 2016 Microsoft