How to access Object by index C#
16,183
Solution 1
Cast the obj
as object[] using:
var list = (object[])obj;
Then you can use list[0]
.
Solution 2
Specify object array type:
object[] obj = item["location_id"];
Or, even simplier, let the compiler infer type:
var obj = item["location_id"];
Related videos on Youtube
Comments
-
nuwaus almost 2 years
I have a foreach loop in C# which return some inventory data, the property
location_id
returns as anobject[]
. the loop as follows,foreach (XmlRpcStruct item in result) { object obj = item["location_id"]; }
in debugger, I see the object as following,
so I guess object is something like
obj[0] = 12 obj[1] = "WH/Stock"
I tried to access the
obj
likeobj[0]
then I getCannot 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
andWH/Stock
-
Dirk Vollmar over 7 years"but that doesn't work": What error do you get?
-
DevOpsSauce over 6 yearsI 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.
-
-
nuwaus over 7 yearsThank you, this worked well for me.
-
Emad over 7 yearsDon't forget to mark the answer. :)
-
nuwaus over 7 yearsTried it already, then you'll get
Cannot implicitly convert type 'object' to 'object[]'. An explicit conversion exists (are you missing a cast?)
compile error. -
Dung over 3 yearsgreat answer, thank you sir @Emad !
-
Dung over 3 yearsIt is also known as boxing and unboxing an object c-sharpcorner.com/blogs/…