Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRichard Külling
9,465 PointsWhy 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
231,248 PointsWhen 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.