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"];
Share:
16,183

Related videos on Youtube

nuwaus
Author by

nuwaus

I love do nothing or coding..

Updated on June 04, 2022

Comments

  • nuwaus
    nuwaus almost 2 years

    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

    • Dirk Vollmar
      Dirk Vollmar over 7 years
      "but that doesn't work": What error do you get?
    • DevOpsSauce
      DevOpsSauce over 6 years
      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.
  • nuwaus
    nuwaus over 7 years
    Thank you, this worked well for me.
  • Emad
    Emad over 7 years
    Don't forget to mark the answer. :)
  • nuwaus
    nuwaus over 7 years
    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.
  • Dung
    Dung over 3 years
    great answer, thank you sir @Emad !
  • Dung
    Dung over 3 years
    It is also known as boxing and unboxing an object c-sharpcorner.com/blogs/…