Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Array Type at runtime

I want to get 'array type' of a type at run time. I do not need the instance of the array, just Type. I currently use the below method.

    private Type GetArrayType(Type elementType)
    {
        return Array.CreateInstance(elementType, 0).GetType();
    }

Is there any better solution without creating the instance of the array?

Note: I cannot use Type.GetType(elementType.FullName + "[]") because I create the element Type at runtime by Reflection.Emit. According to MSDN it requires dynamic assembly to be saved on disk which I do not want to do.

like image 418
Mehmet Ataş Avatar asked Jan 15 '23 05:01

Mehmet Ataş


1 Answers

Yes, you can use Type.MakeArrayType.

Returns a Type object representing a one-dimensional array of the current type, with a lower bound of zero.

private Type GetArrayType(Type elementType)
{
    return elementType.MakeArrayType();
}
like image 115
Ani Avatar answered Jan 17 '23 15:01

Ani