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);
JamesHoux
  • 2,999
  • 3
  • 32
  • 50
  • 1
    [There](https://stackoverflow.com/questions/2085172/) [is](https://stackoverflow.com/questions/11347053/) [so](https://stackoverflow.com/questions/4129831/) [many](https://stackoverflow.com/questions/840878/) [duplicates](https://stackoverflow.com/questions/12267676/) [on](https://stackoverflow.com/questions/5274865/) [stack](https://stackoverflow.com/questions/28624571/) [overflow](https://stackoverflow.com/questions/19072056/) – vasily.sib Jul 08 '19 at 03:25

1 Answers1

1

You can use .GetElementType()

Eg:

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

Documentation

Loocid
  • 6,112
  • 1
  • 24
  • 42
  • 1
    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! – JamesHoux Jul 08 '19 at 03:18