What is the typeof() an array of a Type?

  • Thread starter Thread starter Jon Shemitz
  • Start date Start date
J

Jon Shemitz

Suppose you have a dynamically loaded assembly, Assembly. Suppose you
enumerate all the types in Assembly with Assembly.GetExportedTypes().
Suppose you are working with

Type ExportedType;

which you got from Assembly.GetExportedTypes(). What is the type of an
array of elements of the type ExportedType?

(That is, imagine that within the dynamically loaded assembly, there
is a type BaseType, and ExportedType == typeof(BaseType). How do you
get typeof(BaseType[]) if you only have the ExportedType value?)

I have

internal static Type TypeOfArrayOf(Type AnyType)
{
Array A = Array.CreateInstance(AnyType, 0);
return A.GetType();
}

- is there anything better?
 
Jon Shemitz said:
Suppose you have a dynamically loaded assembly, Assembly. Suppose you
enumerate all the types in Assembly with Assembly.GetExportedTypes().
Suppose you are working with

Type ExportedType;

which you got from Assembly.GetExportedTypes(). What is the type of an
array of elements of the type ExportedType?

(That is, imagine that within the dynamically loaded assembly, there
is a type BaseType, and ExportedType == typeof(BaseType). How do you
get typeof(BaseType[]) if you only have the ExportedType value?)

I have

internal static Type TypeOfArrayOf(Type AnyType)
{
Array A = Array.CreateInstance(AnyType, 0);
return A.GetType();
}

- is there anything better?

I believe you can get the "normal" type name, put "[]" on the end and
use Type.GetType. Both are very unsatisfactory, of course. Fortunately
in .NET 2.0, there'll be a method called MakeArrayType which is exactly
what you want, but for the moment I think one of the options above is
your only way :(
 
Jon Skeet said:
internal static Type TypeOfArrayOf(Type AnyType)
{
Array A = Array.CreateInstance(AnyType, 0);
return A.GetType();
}

- is there anything better?

I believe you can get the "normal" type name, put "[]" on the end and
use Type.GetType. Both are very unsatisfactory, of course. Fortunately
in .NET 2.0, there'll be a method called MakeArrayType which is exactly
what you want, but for the moment I think one of the options above is
your only way :(

Thanks, Jon. That probably would work, too. You're right that neither
is very nice; I suspect (based on what I remember from the last time I
visited this sort of problem) that the CreateInstance approach is
actually faster than string formatting and GetType.
 
Back
Top