George
George

Reputation: 99

C# how to access array info unknown type within object

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.

Upvotes: 2

Views: 2750

Answers (4)

Michael B
Michael B

Reputation: 7567

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.

Upvotes: 2

Juicef
Juicef

Reputation: 316

Another approach would be to use Reflection to determine the type and to manipulate the data. While this is applicable on all types of objects (not only arrays), for the scenario you described I would go with the solution of Jon Skeet.

Upvotes: 0

Adrian Brown
Adrian Brown

Reputation: 466

If they are going to be based on c# object class, you can use GetType() - this will return a System.Type (see http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx). Otherwise you could base them off your own base object that has a type define for all possible values.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499740

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.

Upvotes: 7

Related Questions