Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# initialization array

Can anybody explain, why do I have to use this code pattern?

    // Create the array to store the CDs.
    CD[] cdLibrary = new CD[20];

    // Populate the CD library with CD objects.
    for (int i=0; i<20; i++)
    { cdLibrary[i] = new CD(); }

I cannot understand why the initialization of objects in an array does not occur when I call new CD[20]. It seems like I'm writing excess code. Can one of these steps be skipped?

like image 756
Kirill Golikov Avatar asked Dec 29 '25 17:12

Kirill Golikov


1 Answers

I cannot understand why the initialization of objects in an array does not execute in the operator new.

Do you mean this line?

CD[] cdLibrary = new CD[20];

That doesn't initialize 20 objects. It initializes the array, and only the array - the array has 20 elements, each of which has a value of null (a null reference) to start with1. It's like creating a book with a given number of empty pages; if you want the pages to contain information, you have to write on each one separately, which is what the later loop does.


1 I'm assuming that CD is a class type here, for simplicity.

like image 93
Jon Skeet Avatar answered Jan 01 '26 07:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!