0
Int32[] myArray = new Int32[0];

//Somewhere else in code: 
Type t = myArray.GetType();

//t == Int32[]
//element type of t == ???

How do I find out the element type that t was created to store.

The only example I've found works on arrays that aren't empty, where you simply do myArray[i].GetType(). So what do you do for array length 0?

FYI: I did the following and it works fine, but wow... it uses string conversion and is super ugly. There's got to be a better way:

Type t = myArray.GetType();
string strT = t.ToString();
string strArrayBase = strT.Substring(0, strT.Length - 2);
Type elementType = Type.GetType(strArrayBase);
1

1 Answer 1

1

You can use .GetElementType()

Eg:

> int[] arr = new int[0];
> arr.GetType().GetElementType()
[System.Int32]

Documentation

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

1 Comment

Wow. Fail. I actually looked at the doc on GetElementType(), but the explanation for it seemed kind of confusing. And on some other thread, someone was actually saying not to use it for a similar purpose. So I wasn't sure what to make of it. I just tried it and it works! I feel dumb now. Thanks!

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.