0

I'm trying to get a feel for the syntax of C# and I want to print the elements of an array that's stored inside an element of different array.

int[] numarray = new int[3];
numarray[0] = 5;
numarray[1] = 6;
numarray[2] = 6;
object[] array = new object[6];
array[0] = 1;
array[1] = "string";
array[2] = "test";
array[3] = numarray;
for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}
for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[3].Length); // .Length is an error?
    //how do I print the values of array[3][i]? 
}
3
  • 1
    your array is of type object. Therefore each element in the array is also of type object, and the type object doesn't have a Length property. Commented Aug 7, 2019 at 17:24
  • You're asking for trouble 99% of the time you use the object type. Usually it should be a more specific type and/or means you're doing something "nasty" (like here). Commented Aug 7, 2019 at 17:24
  • 1
    C# is a strongly-typed language. Meaning the compiler will often need you to be very explicit up-casting from object to int[]. Use Console.WriteLine(((int[])array[3]).Length); However, you're generally better off embracing strong-typing and coding in a way where you don't have to up-cast any more than you absolutely have to. Commented Aug 7, 2019 at 17:27

1 Answer 1

1

Your array is of type object. Therefore each element in the array is also of type object, and the type object doesn't have a Length property. So if you want to access that property, you'd have to convert the array[3] into the appropriate type, in this case an array of type int.

Console.WriteLine(((int[])array[3]).Length);

But this is really really bad design. You would only want to use the type object in very limited specific scenarios, as C# is a strongly typed language. So you should re-think your program, and try to use appropriate data structures to store different types of data instead of lumping them into simple object array.

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

2 Comments

so generally you just keep arrays as a single type? What If I need to store an array different elements, should I use a list? an arraylist?
Yes, arrays should generally be of a single type. Re. the second part of the question, you should design your program so that such a need won't arise. You have a number of tools available for that, such as classes and inheritance if you need. But the bottom line is, C# is strongly typed so you should adhere to that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.