CodeDomProvider.GenerateCodeFromCompileUnit Method (CodeCompileUnit, TextWriter, CodeGeneratorOptions)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Generates code for the specified Code Document Object Model (CodeDOM) compilation unit and sends it to the specified text writer, using the specified options.

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

public virtual void GenerateCodeFromCompileUnit(
	CodeCompileUnit compileUnit,
	TextWriter writer,
	CodeGeneratorOptions options


Type: System.CodeDom.CodeCompileUnit

A CodeCompileUnit for which to generate code.

Type: System.IO.TextWriter

The TextWriter to which the output code is sent.

Type: System.CodeDom.Compiler.CodeGeneratorOptions

A CodeGeneratorOptions that indicates the options to use for generating code.

Exception Condition

Neither this method nor the CreateGenerator method is overridden in a derived class.


In the .NET Framework versions 1.0 and 1.1, this method is provided by the ICodeGenerator implementation that is returned by the CreateGenerator method of the provider. In version 2.0, this method can be called directly on the code provider even if it is not overridden by the code provider. If the code provider does not override this method, the ICodeGenerator implementation is called by the base class.

Notes to Inheritors:

If you override this method, you must not call the corresponding method of the base class. The base-class method creates a generator in the derived class using the obsolete CreateGenerator method for compatibility with preexisting providers that use code generators. The base-class method then calls the equivalent method in the ICodeGenerator implementation to perform this function. You will get a NotImplementedException if you call the base-class method from a code provider that does not use a code generator.

The following code example shows the use of the GenerateCodeFromCompileUnit method to generate code for a "Hello World" application from a CodeCompileUnit. This example is part of a larger example provided for the CodeDomProvider class.

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.

.NET Framework
Available since 2.0
Return to top