Defining new field of array type (Reflection.Emit)

Hi,

Im generating a new array type with the TypeBuilder.MakeArrayType function, than defining a field with the array type i've created. How can i set the field with a specified length

I want the field to be myType[2] instead of myType[].

Please help me...




Answer this question

Defining new field of array type (Reflection.Emit)

  • Witi

    So how can I instaniate the new array with specified length

    I didnt find in the FieldBuilder class an option to do this.



  • Mostafa Omar

    So using the Activator.createInstance how would this look

    I have an interface, but I don`t know which implementation I am using at the moment.

    For example, I have the type theat implements Interface1:

    <code>

    Type type = getImplementedTypeFromSomeWhereElse();

    // I then have a list of type: IList<Interface1>
    IList<Interface1> list = getPopulatedListFromSomeWhereElse();

    // Then I need to create the array
    Interface1[] objects = Activator.CreateInstance(type.MakeArrayType());

    // How do I set the length

    // Copy list objects to the array
    for (int i = 0; i < list.Count; i++)
    {
    objects = list[ i ];
    }

    </code>

    Thanks,

  • bodalal

    In this case you use Array.CreateInstance instead.

    Interface1[] objects = (Interface1[])Array.CreateInstance(type, arrayLength);



  • LMcFarlin

    You generate code (in a constructor for example) that creates it using the newarr opcode.

    If you're not sure how it should look like, compile the corresponding C# code and look at it with Ildasm.

    class Test { Test[] t = new Test[2]; }



  • Aleborg

    The length of an array is not a property of its type, it's a property of the instance. You set it when you instantiate the array, the field type is still myType[].



  • Defining new field of array type (Reflection.Emit)