This documentation is archived and is not being maintained.

CodeTypeParameter Class

Represents a type parameter of a generic type or method.


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

public class CodeTypeParameter : CodeObject

The CodeTypeParameter type exposes the following members.

Public methodCodeTypeParameter()Initializes a new instance of the CodeTypeParameter class.
Public methodCodeTypeParameter(String)Initializes a new instance of the CodeTypeParameter class with the specified type parameter name.

Public propertyConstraintsGets the constraints for the type parameter.
Public propertyCustomAttributesGets the custom attributes of the type parameter.
Public propertyHasConstructorConstraintGets or sets a value indicating whether the type parameter has a constructor constraint.
Public propertyNameGets or sets the name of the type parameter.
Public propertyUserDataGets the user-definable data for the current object. (Inherited from CodeObject.)

Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)

The CodeTypeParameter class represents a type parameter in the declaration of a generic type or method.

A generic type or method declaration contains one or more unspecified types known as type parameters. A type parameter name stands for the type within the body of the generic declaration. For example, the generic declaration for the List<T> class contains the type parameter T.

For more information on generics, see Generics in the .NET Framework Class Library (C# Programming Guide).

The following code example shows the use of the CodeTypeParameter class to create a CodeDOM graph to generate an application containing generics code.

using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections.Generic;
namespace System.CodeDom
    class CodeDomGenericsDemo
        static void Main()
                CreateGenericsCode("cs", "Generic.cs", "GenericCS.exe");
            catch (Exception e)
                LogMessage("Unexpected Exception:" + e.ToString());

        static void CreateGenericsCode(string providerName, string sourceFileName, string assemblyName)

            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);

            LogMessage("Building CodeDOM graph...");

            CodeCompileUnit cu = new CodeCompileUnit();

            CreateGraph(provider, cu);

            StringWriter sw = new StringWriter();

            LogMessage("Generating code...");
            provider.GenerateCodeFromCompileUnit(cu, sw, null);

            string output = sw.ToString();
            output = Regex.Replace(output, "Runtime Version:[^\r\n]*",
                "Runtime Version omitted for demo");

            LogMessage("Dumping source...");

            LogMessage("Writing source to file...");
            Stream s = File.Open(sourceFileName, FileMode.Create);
            StreamWriter t = new StreamWriter(s);

            CompilerParameters opt = new CompilerParameters(new string[]{
            opt.GenerateExecutable = false;
            opt.TreatWarningsAsErrors = true;
            opt.IncludeDebugInformation = true;
            opt.GenerateInMemory = true;

            CompilerResults results;

            LogMessage("Compiling with " + providerName);
            results = provider.CompileAssemblyFromFile(opt, sourceFileName);

            if (results.NativeCompilerReturnValue != 0)
                LogMessage("Compilation failed.");
                LogMessage("Demo completed successfully.");

        // Create a CodeDOM graph.
        static void CreateGraph(CodeDomProvider provider, CodeCompileUnit cu)
            if (!provider.Supports(GeneratorSupport.GenericTypeReference |
                // Return if the generator does not support generics.

            CodeNamespace ns = new CodeNamespace("DemoNamespace");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            // Declare a generic class.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary",
                                      new CodeTypeReference[] {
                                          new CodeTypeReference("TKey"),    
                                          new CodeTypeReference("TValue"),    
            CodeTypeParameter kType = new CodeTypeParameter("TKey");
            kType.HasConstructorConstraint = true;
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                    new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));


            CodeTypeParameter vType = new CodeTypeParameter("TValue");
            vType.Constraints.Add(new CodeTypeReference(typeof(IList<System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                    new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));



            // Declare a generic method.
            CodeMemberMethod printMethod = new CodeMemberMethod();
            CodeTypeParameter sType = new CodeTypeParameter("S");
            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");
            sType.HasConstructorConstraint = true;

            printMethod.Name = "Print";

                new CodeDefaultValueExpression(new CodeTypeReference("T"))));
                new CodeDefaultValueExpression(new CodeTypeReference("S"))));

            printMethod.Attributes = MemberAttributes.Public;

            CodeTypeDeclaration class2 = new CodeTypeDeclaration();
            class2.Name = "Demo";

            CodeEntryPointMethod methodMain = new CodeEntryPointMethod();

            CodeTypeReference myClass = new CodeTypeReference(
                new CodeTypeReference[] {
                    new CodeTypeReference(typeof(int)),
                    new CodeTypeReference("List", 
                       new CodeTypeReference[] 
                            {new CodeTypeReference("System.String") })});

                  new CodeVariableDeclarationStatement(myClass,
                          new CodeObjectCreateExpression(myClass)));

                new CodePropertyReferenceExpression(
                      new CodeVariableReferenceExpression("dict"),

            methodMain.Statements.Add(new CodeExpressionStatement(
                 new CodeMethodInvokeExpression(
                      new CodeMethodReferenceExpression(
                         new CodeVariableReferenceExpression("dict"),
                                 new CodeTypeReference[] {
                                    new CodeTypeReference("System.Decimal"),
                                       new CodeTypeReference("System.Int32"),}),
                                           new CodeExpression[0])));

            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int,

            CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName);
                  new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) })));

                           new CodePropertyReferenceExpression(
                                new CodeVariableReferenceExpression("dict2"),



        static CodeStatement ConsoleWriteLineStatement(CodeExpression exp)
            return new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                   new CodeMethodReferenceExpression(
                       new CodeTypeReferenceExpression(new CodeTypeReference("Console")),
                               new CodeExpression[]{

        static CodeStatement ConsoleWriteLineStatement(string text)
            return ConsoleWriteLineStatement(new CodePrimitiveExpression(text));
        static void LogMessage(string text)

        static void OutputResults(CompilerResults results)
            LogMessage("NativeCompilerReturnValue=" +
            foreach (string s in results.Output)

// This example generates the following code:
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version omitted for demo
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>

//namespace DemoNamespace
//    using System;
//    using System.Collections.Generic;

//    public class MyDictionary<[System.ComponentModel.DescriptionAttribute("KeyType")]  TKey,
//          [System.ComponentModel.DescriptionAttribute("ValueType")]  TValue> : Dictionary<TKey, TValue>
//        where TKey : System.IComparable, IComparable<TKey>, new()
//        where TValue : System.Collections.Generic.IList<string>
//    {

//        public virtual void Print<S, T>()
//            where S : new()
//        {
//            Console.WriteLine(default(T));
//            Console.WriteLine(default(S));
//        }
//    }

//    public class Demo
//    {

//        public static void Main()
//        {
//            MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>();
//            Console.WriteLine(dict.Count);
//            dict.Print<decimal, int>();
//            System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] dict2 =
//              new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] { null };
//            Console.WriteLine(dict2.Length);
//        }
//    }

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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