CompilerParameters Class


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

Represents the parameters used to invoke a compiler.

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

[PermissionSetAttribute(SecurityAction::LinkDemand, Name = "FullTrust")]
[PermissionSetAttribute(SecurityAction::InheritanceDemand, Name = "FullTrust")]
public ref class CompilerParameters 


Initializes a new instance of the CompilerParameters class.


Initializes a new instance of the CompilerParameters class using the specified assembly names.

System_CAPS_pubmethodCompilerParameters(array<String^>^, String^)

Initializes a new instance of the CompilerParameters class using the specified assembly names and output file name.

System_CAPS_pubmethodCompilerParameters(array<String^>^, String^, Boolean)

Initializes a new instance of the CompilerParameters class using the specified assembly names, output name, and a value indicating whether to include debug information.


Gets or sets optional command-line arguments to use when invoking the compiler.


Gets or sets the name of the core or standard assembly that contains basic types such as Object, String, or Int32.


Gets the .NET Framework resource files to include when compiling the assembly output.


Obsolete. Specifies an evidence object that represents the security policy permissions to grant the compiled assembly.


Gets or sets a value indicating whether to generate an executable.


Gets or sets a value indicating whether to generate the output in memory.


Gets or sets a value indicating whether to include debug information in the compiled executable.


Gets the .NET Framework resource files that are referenced in the current source.


Gets or sets the name of the main class.


Gets or sets the name of the output assembly.


Gets the assemblies referenced by the current project.


Gets or sets the collection that contains the temporary files.


Gets or sets a value indicating whether to treat warnings as errors.


Gets or sets the user token to use when creating the compiler process.


Gets or sets the warning level at which the compiler aborts compilation.


Gets or sets the file name of a Win32 resource file to link into the compiled assembly.


Determines whether the specified object is equal to the current object.(Inherited from Object.)


Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)


Serves as the default hash function. (Inherited from Object.)


Gets the Type of the current instance.(Inherited from Object.)


Creates a shallow copy of the current Object.(Inherited from Object.)


Returns a string that represents the current object.(Inherited from Object.)

A CompilerParameters object represents the settings and options for an ICodeCompiler interface.

If you are compiling an executable program, you must set the GenerateExecutable property to true. When the GenerateExecutable is set to false, the compiler will generate a class library. By default, a new CompilerParameters is initialized with its GenerateExecutable property set to false. If you are compiling an executable from a CodeDOM graph, a CodeEntryPointMethod must be defined in the graph. If there are multiple code entry points, you can indicate the class that defines the entry point to use by setting the name of the class to the MainClass property.

You can specify a file name for the output assembly in the OutputAssembly property. Otherwise, a default output file name will be used. To include debug information in a generated assembly, set the IncludeDebugInformation property to true. If your project references any assemblies, you must specify the assembly names as items in a StringCollection set to the ReferencedAssemblies property of the CompilerParameters used when invoking compilation.

You can compile an assembly that is written to memory rather than disk by setting the GenerateInMemory property to true. When an assembly is generated in memory, your code can obtain a reference to the generated assembly from the CompiledAssembly property of a CompilerResults. If an assembly is written to disk, you can obtain the path to the generated assembly from the PathToAssembly property of a CompilerResults.

To specify a warning level at which to halt compilation, set the WarningLevel property to an integer that represents the warning level at which to halt compilation. You can also configure the compiler to halt compilation if warnings are encountered by setting the TreatWarningsAsErrors property to true.

To specify a custom command-line arguments string to use when invoking the compilation process, set the string in the CompilerOptions property. If a Win32 security token is required to invoke the compiler process, specify the token in the UserToken property. To include .NET Framework resource files in the compiled assembly, add the names of the resource files to the EmbeddedResources property. To reference .NET Framework resources in another assembly, add the names of the resource files to the LinkedResources property. To include a Win32 resource file in the compiled assembly, specify the name of the Win32 resource file in the Win32Resource property.


This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when 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.

The following example builds a CodeDOM source graph for a simple Hello World program. The source is then saved to a file, compiled into an executable, and run. The CompileCode method illustrates how to use the CompilerParameters class to specify various compiler settings and options.

using namespace System;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Diagnostics;

// Build a Hello World program graph using System.CodeDom types.
static CodeCompileUnit^ BuildHelloWorldGraph()
   // Create a new CodeCompileUnit to contain the program graph.
   CodeCompileUnit^ compileUnit = gcnew CodeCompileUnit;

   // Declare a new namespace called Samples.
   CodeNamespace^ samples = gcnew CodeNamespace( "Samples" );
   // Add the new namespace to the compile unit.
   compileUnit->Namespaces->Add( samples );

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

   // Declare a new type called Class1.
   CodeTypeDeclaration^ class1 = gcnew CodeTypeDeclaration( "Class1" );
   // Add the new type to the namespace's type collection.
   samples->Types->Add( class1 );

   // Declare a new code entry point method
   CodeEntryPointMethod^ start = gcnew CodeEntryPointMethod;

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

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

   // Add the WriteLine call to the statement collection.
   start->Statements->Add( cs1 );

   // Build another Console::WriteLine statement.
   CodeMethodInvokeExpression^ cs2 = gcnew CodeMethodInvokeExpression(
      csSystemConsoleType, "WriteLine",
      gcnew CodePrimitiveExpression( "Press the Enter key to continue." ) );
   // Add the WriteLine call to the statement collection.
   start->Statements->Add( cs2 );

   // Build a call to System::Console::ReadLine.
   CodeMethodReferenceExpression^ csReadLine = gcnew CodeMethodReferenceExpression(
      csSystemConsoleType, "ReadLine" );
   CodeMethodInvokeExpression^ cs3 = gcnew CodeMethodInvokeExpression(
      csReadLine,gcnew array<CodeExpression^>(0) );

   // Add the ReadLine statement.
   start->Statements->Add( cs3 );

   // Add the code entry point method to the Members collection
   // of the type.
   class1->Members->Add( start );

   return compileUnit;

static String^ GenerateCode( CodeDomProvider^ provider, CodeCompileUnit^ compileunit )
   // Build the source file name with the language extension (vb, cs, js).
   String^ sourceFile = String::Empty;

      if ( provider->FileExtension->StartsWith( "." ) )
         sourceFile = String::Concat( "HelloWorld", provider->FileExtension );
         sourceFile = String::Concat( "HelloWorld.", provider->FileExtension );

      // Create a TextWriter to a StreamWriter to an output file.
      IndentedTextWriter^ tw = gcnew IndentedTextWriter(
         gcnew StreamWriter( sourceFile,false ),"    " );
      // Generate source code using the code generator.
      provider->GenerateCodeFromCompileUnit( compileunit, tw, gcnew CodeGeneratorOptions );
      // Close the output file.
   return sourceFile;

static bool CompileCode( CodeDomProvider^ provider,
   String^ sourceFile,
   String^ exeFile )

   CompilerParameters^ cp = gcnew CompilerParameters;
   if ( !cp)  
      return false;

   // Generate an executable instead of 
   // a class library.
   cp->GenerateExecutable = true;

   // Set the assembly file name to generate.
   cp->OutputAssembly = exeFile;

   // Generate debug information.
   cp->IncludeDebugInformation = true;

   // Add an assembly reference.
   cp->ReferencedAssemblies->Add( "System.dll" );

   // Save the assembly as a physical file.
   cp->GenerateInMemory = false;

   // Set the level at which the compiler 
   // should start displaying warnings.
   cp->WarningLevel = 3;

   // Set whether to treat all warnings as errors.
   cp->TreatWarningsAsErrors = false;

   // Set compiler argument to optimize output.
   cp->CompilerOptions = "/optimize";

   // Set a temporary files collection.
   // The TempFileCollection stores the temporary files
   // generated during a build in the current directory,
   // and does not delete them after compilation.
   cp->TempFiles = gcnew TempFileCollection( ".",true );

   if ( provider->Supports( GeneratorSupport::EntryPointMethod ) )
      // Specify the class that contains 
      // the main method of the executable.
      cp->MainClass = "Samples.Class1";

   if ( Directory::Exists( "Resources" ) )
      if ( provider->Supports( GeneratorSupport::Resources ) )
         // Set the embedded resource file of the assembly.
         // This is useful for culture-neutral resources,
         // or default (fallback) resources.
         cp->EmbeddedResources->Add( "Resources\\Default.resources" );

         // Set the linked resource reference files of the assembly.
         // These resources are included in separate assembly files,
         // typically localized for a specific language and culture.
         cp->LinkedResources->Add( "Resources\\nb-no.resources" );

   // Invoke compilation.
   CompilerResults^ cr = provider->CompileAssemblyFromFile( cp, sourceFile );

   if ( cr->Errors->Count > 0 )
      // Display compilation errors.
      Console::WriteLine( "Errors building {0} into {1}",
         sourceFile, cr->PathToAssembly );
      for each ( CompilerError^ ce in cr->Errors )
         Console::WriteLine( "  {0}", ce->ToString() );
      Console::WriteLine( "Source {0} built into {1} successfully.",
         sourceFile, cr->PathToAssembly );

   // Return the results of compilation.
   if ( cr->Errors->Count > 0 )
      return false;
      return true;

void main()
   String^ exeName = "HelloWorld.exe";
   CodeDomProvider^ provider = nullptr;

   Console::WriteLine( "Enter the source language for Hello World (cs, vb, etc):" );
   String^ inputLang = Console::ReadLine();

   if ( CodeDomProvider::IsDefinedLanguage( inputLang ) )
      CodeCompileUnit^ helloWorld = BuildHelloWorldGraph();
      provider = CodeDomProvider::CreateProvider( inputLang );
      if ( helloWorld && provider )
         String^ sourceFile = GenerateCode( provider, helloWorld );
         Console::WriteLine( "HelloWorld source code generated." );
         if ( CompileCode( provider, sourceFile, exeName ) )
            Console::WriteLine( "Starting HelloWorld executable." );
            Process::Start( exeName );

   if ( provider == nullptr )
      Console::WriteLine( "There is no CodeDomProvider for the input language." );


for full trust for the immediate caller. This class cannot be used by partially trusted code.


for full trust for inheritors. This class cannot be inherited by partially trusted code.

.NET Framework
Available since 1.1

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

Return to top