Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C#

Richard Külling
Richard Külling
9,465 Points

Why does new Cell[3] in repl output {null,null,null} instead of {Cell, Cell, Cell}

So I was wondering why in the video, where they make a spreadsheet, the Cell class: class Cell { public string Contents { get; set; } } shows up as a collection of null-values when initialized with: Cell[][] sheet = new Cell[100][]; //outputs 100x null: {null, null, null...}

or even when initialized with: sheet[rowIndex] = new Cell[10]; //outputs 100 x 10 x null

And only the following line, contained in a nested loop, will finally change the null-values into 'Cell' objects: sheet[rowIndex][colIndex] = new Cell(); //outputs: {Cell, Cell, Cell...}

This doesn't make sense to me, since both 'new Cell[] ' and 'new Cell()' have no input value, yet Cell() instanciates a {Cell}, and Cell[3] instanciates {null, null, null}, so basically the object clarification at the time of array initialization seems pointless, at least to me. So why does C# not leave out the specification to the Cell class until it matters, like so: [][] sheet = new [100][]; for (int i = 0; i < 100; i++) { sheet[i] = new [10]; for (int j = 0; j < 10; j++) { sheet[i][j] = Cell(); } }

What in particular does the 'Cell' keyword do at the time of (jagged) Array initialization?

1 Answer

Steven Parker
Steven Parker
216,012 Points

When you allocate a Cell array ("new Cell[]") you create space to store new Cell objects, but the objects themselves (the new Cell instances) are not created. That's why the array elements still contain null.

But the reason for naming the object type when you create the array is for the compiler to know what kind (and what size) objects will eventually be stored so it can allocate the right amount of storage space.