1

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!

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, well that's fair enough. But what if you're given "string[]" as the input instead of "System.String[]"?
@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.
I see, but I think I'll pass on the keyword dictionary! Thanks for your help.
4

Use GetElementType() on the type:

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

ttt is of type String.

Comments

0

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.

Comments

0

The type is System.String[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.