views:

87

answers:

4

Given the string "string[]" and asked to get the underlying Type for this class, one might start with:

private Type getTypeByName(string typeName)
{
    if (typeName.EndsWith("[]"))
    {
           return something; // But what? 
    }

    return Type.GetType(typeName);
}

What type is "string[]" and how does one reflect the type out of it?

Obviously there's a System.String type and a System.Array type, but I can't see how they can be reflected "together" as you would normally do for Nullable<T> and its T with the MakeGenericType method.

Any help to break the mind-loop I've gotten myself into will be greatly appreciated!

+7  A: 

What exactly is your problem? Type.GetType works fine:

Console.WriteLine(typeof(string[]));
var type = Type.GetType("System.String[]");
Console.WriteLine(type);

Prints:

System.String[]
System.String[]

so clearly this works as expected.

Konrad Rudolph
Ah, well that's fair enough. But what if you're given "string[]" as the input instead of "System.String[]"?
tags2k
@tags: well, `string` is a C# keyword, it’s not a CLR/CTS type so you can’t really expect the CLR to know about it. If you absolutely must use it, put all the C# keyword type mappings into a dictionary and use the dictionary to replace those types in your input strings.
Konrad Rudolph
I see, but I think I'll pass on the keyword dictionary! Thanks for your help.
tags2k
A: 

Type.GetType("System.String[]") will returns the string array type. No need to check for [] in your input string.

You can verity this by checking the Type.IsArray prop.

Fabian Vilers
+1  A: 

Use GetElementType() on the type:

string[] eee = new string[1];
Type ttt = eee.GetType().GetElementType();

ttt is of type String.

Mart
A: 

The type is System.String[]

Henrik