Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to access array info unknown type within object

Tags:

c#

I have an object called SampleObject that holds an array of strings called StringArray. In order for me to access the first element in that array I need to write:

((string[])(SampleObject))[0]

However if I were to not know the type of the array how would I be able to approach this?

((SampleObject.GetType())(SampleObject))[0];

I tried something like this but it expects a method name.

Thanks.

like image 822
George Avatar asked Dec 07 '25 08:12

George


2 Answers

You can use Array.GetValue - all array types are derived from Array, whatever the element type is. You may need to think carefully about rectangular arrays though, and arrays with a non-zero lower bound.

like image 110
Jon Skeet Avatar answered Dec 08 '25 20:12

Jon Skeet


While Jon's answer is correct, you can abuse array co-variance, provided you have a normal (one dimensional, starting at 0) array of reference type.

return ((object[])SampleObject)[3];

Return the 3rd element in the array. You can also cast it to a non-generic IList if it not only will change the element type, but possibly the container itself.

like image 41
Michael B Avatar answered Dec 08 '25 22:12

Michael B