2

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.

1
  • Would you even be sure it is an array? Commented Oct 24, 2011 at 15:47

4 Answers 4

8

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.

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

2 Comments

So something on the lines of ((string[])(SampleObject)).GetValue.
@George, going by you not knowing the appropriate type, it would be something like var array = (Array)SampleObject; var item = array.GetValue(0); This will, of course, blow up quite spectacularly if SampleObject isn't actually an array.
2

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.

2 Comments

While this is true, and you did specify reference types, it all goes to pot as soon as the object holds an int[].
true, but then the ILIst approach is best as then you aren't tied to the container.
0

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.

Comments

0

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.

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.