TypeBuilder.GetConstructor Method (Type, ConstructorInfo)

Returns the constructor of the specified constructed generic type that corresponds to the specified constructor of the generic type definition.

Namespace:  System.Reflection.Emit
Assembly:  mscorlib (in mscorlib.dll)

public static ConstructorInfo GetConstructor(
	Type type,
	ConstructorInfo constructor
)

Parameters

type
Type: System.Type

The constructed generic type whose constructor is returned.

constructor
Type: System.Reflection.ConstructorInfo

A constructor on the generic type definition of type, which specifies which constructor of type to return.

Return Value

Type: System.Reflection.ConstructorInfo
A ConstructorInfo object that represents the constructor of type corresponding to constructor, which specifies a constructor belonging to the generic type definition of type.

ExceptionCondition
ArgumentException

type does not represent a generic type.

-or-

type is not of type TypeBuilder.

-or-

The declaring type of constructor is not a generic type definition.

-or-

The declaring type of constructor is not the generic type definition of type.

The GetConstructor method provides a way to get a ConstructorInfo object that represents a constructor of a constructed generic type whose generic type definition is represented by a TypeBuilder object.

For example, suppose you have a TypeBuilder object that represents the type G<T> in C# syntax (G(Of T) in Visual Basic, generic <T> ref class G in C++) and a ConstructorBuilder object that represents a constructor of G<T>. Suppose that G<T> has a generic method with type parameter U that creates an instance of the constructed type G<U>. In order to emit the code to create an instance of the constructed type, you need a ConstructorInfo object that represents the constructor of this constructed type — in other words, that creates an instance of G<U>. To do this, first call the MakeGenericType method on the TypeBuilder object, specifying the GenericTypeParameterBuilder object that represents U as the type argument. Then call the GetConstructor method with the return value of the MakeGenericType method as parameter type and the ConstructorBuilder object that represents the constructor of G<U> as parameter constructor. The return value is the ConstructorInfo object you need to emit the function call. The code example demonstrates this scenario.

The following code example contains source code for a generic class named Sample that has a type parameter named T. The class has a field named Field, of type T, and a generic method named GM with its own type parameter, named U. Method GM creates an instance of Sample, substituting its own type parameter U for the type parameter of Sample, and stores its input parameter in Field. This source code is compiled but not used; you can view it with the Ildasm.exe (IL Disassembler) and compare it to the code emitted by class Example.

The code in class Example demonstrates the use of the GetConstructor method to emit generic code. The Main method of class Example creates a dynamic assembly containing a class named Sample and uses the DefineGenericParameters method to make it generic by adding a type parameter named T. A default constructor and a field named Field, of type T, are added to class Sample. A method GM is added and turned into a generic method by using the MethodBuilder.DefineGenericParameters method. The type parameter of GM is named U. After the type parameter is defined, the signature of GM is added by using the MethodBuilder.SetSignature method. There is no return type and no required or custom modifiers, so all the parameters of this method are null except parameterTypes; parameterTypes sets the type of the method's only parameter to U, the method's generic type parameter. The body of the method creates an instance of the constructed type Sample<U> (Sample(Of U) in Visual Basic), assigns the method's parameter to Field, and then prints the value of Field. The GetConstructor method is used to create a ConstructorInfo that represents the default constructor of the constructed generic type Sample<U> in the OpCodes.Newobj instruction that creates the instance.

A dummy type is defined to hold the entry-point method Main. In the body of Main, the static GM method is invoked on the constructed generic type Sample<int> (Sample(Of Integer) in Visual Basic), with type String substituted for U.

When the code example is run, it saves the emitted assembly as TypeBuilderGetFieldExample.exe. You can run TypeBuilderGetFieldExample.exe, and you can use the Ildasm.exe (IL Disassembler) to compare the emitted code with the code for the Sample class that is compiled into the code example itself.

using System;
using System.Reflection;
using System.Reflection.Emit;

// Compare the MSIL in this class to the MSIL 
// generated by the Reflection.Emit code in class 
// Example. 
public class Sample<T>
{
  public T Field;
  public static void GM<U>(U val)
  {
    Sample<U> s = new Sample<U>();
    s.Field = val;
    Console.WriteLine(s.Field);
  }
}

public class Example
{
    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName myAsmName = 
            new AssemblyName("TypeBuilderGetFieldExample");
        AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
            myAsmName, AssemblyBuilderAccess.Save);
        ModuleBuilder myModule = myAssembly.DefineDynamicModule(
            myAsmName.Name, 
            myAsmName.Name + ".exe");

        // Define the sample type.
        TypeBuilder myType = myModule.DefineType("Sample", 
            TypeAttributes.Class | TypeAttributes.Public);

        // Add a type parameter, making the type generic. 
        string[] typeParamNames = {"T"};  
        GenericTypeParameterBuilder[] typeParams = 
            myType.DefineGenericParameters(typeParamNames);

        // Define a default constructor. Normally it would  
        // not be necessary to define the default constructor, 
        // but in this case it is needed for the call to 
        // TypeBuilder.GetConstructor, which gets the default 
        // constructor for the generic type constructed from  
        // Sample<T>, in the generic method GM<U>.
        ConstructorBuilder ctor = myType.DefineDefaultConstructor(
            MethodAttributes.PrivateScope | MethodAttributes.Public |
            MethodAttributes.HideBySig | MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        // Add a field of type T, with the name Field.
        FieldBuilder myField = myType.DefineField("Field", 
            typeParams[0],
            FieldAttributes.Public);

        // Add a method and make it generic, with a type  
        // parameter named U. Note how similar this is to  
        // the way Sample is turned into a generic type. The 
        // method has no signature, because the type of its 
        // only parameter is U, which is not yet defined.
        MethodBuilder genMethod = myType.DefineMethod("GM", 
            MethodAttributes.Public | MethodAttributes.Static);
        string[] methodParamNames = {"U"};
        GenericTypeParameterBuilder[] methodParams = 
            genMethod.DefineGenericParameters(methodParamNames);

        // Now add a signature for genMethod, specifying U 
        // as the type of the parameter. There is no return value 
        // and no custom modifiers.
        genMethod.SetSignature(null, null, null, 
            new Type[] { methodParams[0] }, null, null);

        // Emit a method body for the generic method.
        ILGenerator ilg = genMethod.GetILGenerator();
        // Construct the type Sample<U> using MakeGenericType.
        Type SampleOfU = myType.MakeGenericType( methodParams[0] );
        // Create a local variable to store the instance of 
        // Sample<U>.
        ilg.DeclareLocal(SampleOfU);
        // Call the default constructor. Note that it is  
        // necessary to have the default constructor for the 
        // constructed generic type Sample<U>; use the  
        // TypeBuilder.GetConstructor method to obtain this  
        // constructor.
        ConstructorInfo ctorOfU = TypeBuilder.GetConstructor(
            SampleOfU, ctor);
        ilg.Emit(OpCodes.Newobj, ctorOfU);
        // Store the instance in the local variable; load it 
        // again, and load the parameter of genMethod.
        ilg.Emit(OpCodes.Stloc_0); 
        ilg.Emit(OpCodes.Ldloc_0); 
        ilg.Emit(OpCodes.Ldarg_0);
        // In order to store the value in the field of the 
        // instance of Sample<U>, it is necessary to have  
        // a FieldInfo representing the field of the  
        // constructed type. Use TypeBuilder.GetField to  
        // obtain this FieldInfo.
        FieldInfo FieldOfU = TypeBuilder.GetField(
            SampleOfU, myField);
        // Store the value in the field. 
        ilg.Emit(OpCodes.Stfld, FieldOfU);
        // Load the instance, load the field value, box it 
        // (specifying the type of the type parameter, U), and 
        // print it.
        ilg.Emit(OpCodes.Ldloc_0);
        ilg.Emit(OpCodes.Ldfld, FieldOfU);
        ilg.Emit(OpCodes.Box, methodParams[0]);
        MethodInfo writeLineObj = 
            typeof(Console).GetMethod("WriteLine", 
                new Type[] { typeof(object) });
        ilg.EmitCall(OpCodes.Call, writeLineObj, null);
        ilg.Emit(OpCodes.Ret);

        // Emit an entry point method; this must be in a 
        // non-generic type.
        TypeBuilder dummy = myModule.DefineType("Dummy", 
            TypeAttributes.Class | TypeAttributes.NotPublic);
        MethodBuilder entryPoint = dummy.DefineMethod("Main", 
            MethodAttributes.Public | MethodAttributes.Static,
            null, null);
        ilg = entryPoint.GetILGenerator();
        // In order to call the static generic method GM, it is 
        // necessary to create a constructed type from the  
        // generic type definition for Sample. This can be any 
        // constructed type; in this case Sample<int> is used.
        Type SampleOfInt = 
            myType.MakeGenericType( typeof(int) );
        // Next get a MethodInfo representing the static generic 
        // method GM on type Sample<int>.
        MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, 
            genMethod);
        // Next get a MethodInfo for GM<string>, which is the  
        // instantiation of GM that Main calls.
        MethodInfo GMOfString = 
            SampleOfIntGM.MakeGenericMethod( typeof(string) );
        // Finally, emit the call. Push a string onto 
        // the stack, as the argument for the generic method.
        ilg.Emit(OpCodes.Ldstr, "Hello, world!");
        ilg.EmitCall(OpCodes.Call, GMOfString, null);
        ilg.Emit(OpCodes.Ret);

        myType.CreateType();
        dummy.CreateType();
        myAssembly.SetEntryPoint(entryPoint);
        myAssembly.Save(myAsmName.Name + ".exe");

        Console.WriteLine(myAsmName.Name + ".exe has been saved.");
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft