10

I have a foreach loop in C# which return some inventory data, the property location_id returns as an object[]. the loop as follows,

foreach (XmlRpcStruct item in result)
{
   object obj =  item["location_id"];
}

in debugger, I see the object as following, enter image description here

so I guess object is something like

obj[0] = 12
obj[1] = "WH/Stock"

I tried to access the obj like obj[0] then I get

Cannot apply indexing with [] to an expression of type 'object'

So, how can I access the object by index to retrieve the values such as 12 and WH/Stock

5
  • 1
    "but that doesn't work": What error do you get? Commented Dec 1, 2016 at 7:22
  • When trying with obj[0] did you get an compiler error or an execution error or something? Commented Dec 1, 2016 at 7:22
  • Yes, I tried that, then i get the error cannot apply indexing with[] to an expression of type 'object' Commented Dec 1, 2016 at 7:22
  • have a look at this answer Commented Dec 1, 2016 at 7:26
  • 1
    I don't know why this was "Closed as off topic" because I'm struggling with the exact same thing. Gotta love SO and their hubris. Commented Nov 20, 2017 at 19:58

2 Answers 2

18

Cast the obj as object[] using:

var list = (object[])obj;

Then you can use list[0].

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

3 Comments

Thank you, this worked well for me.
Don't forget to mark the answer. :)
It is also known as boxing and unboxing an object c-sharpcorner.com/blogs/…
1

Specify object array type:

object[] obj =  item["location_id"];

Or, even simplier, let the compiler infer type:

var obj =  item["location_id"];

1 Comment

Tried it already, then you'll get Cannot implicitly convert type 'object' to 'object[]'. An explicit conversion exists (are you missing a cast?) compile error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.