2

Let's say we declare an array of type Person with size 3:

Person[] arr = new Person[3];

After that , why do I still have to do:

arr[i] = new Person();

I thought new Person[3] creates 3 persons in memory , and arr will point to the first one.Thanks!

5 Answers5

3

I thought new Person[3] creates 3 persons in memory, and arr will point to the first one.

Nope, it just creates an array that can store references to 3 persons (assuming that Person is a class rather than a struct). After all, how should C# know what exactly you want to store in there? It could be a reference to a Person, it could be a null reference, it could be a reference to a Student (a subclass of Person), ... And Person might not even have a constructor without parameters!

In a nutshell, this:

Person[] arr = new Person[3];

creates this:

+--------+--------+--------+
| null   | null   | null   |
+--------+--------+--------+

And you can now fill that array with values, e.g.

var john = new Person("John Doe");
arr[0] = john;
arr[1] = john;
arr[2] = new Student("Mike", "Computer Science");

Resulting in:

+--------+--------+--------+
|  ref   |  ref   |  ref   |
+--------+--------+--------+
    |         |        |
    |      +--+        +------+
    |      |                  |
    v      v                  v
+-------------+         +------------+
|  Person     |         | Student    |
+-------------+         +------------+
| John Doe    |         | Mike       |
+-------------+         | Comp.Sci.  |
                        +------------+
Heinzi
  • 167,459
  • 57
  • 363
  • 519
2

When you use single-dimension arrays in C# they can be initialized in a couple different ways.

When you initialize a reference type single dimension array, the default value for every index is always null(or default for some reference types).

This is counter-intuitive to the way value typed arrays initialize, which initialize to whatever the default value is for that value type, which is usually 0(at least when talking about primitives).

The reason reference typed arrays don't initialize with meaningful values is because the language has no way to know what you intend to be a default value for a class like Person, is the default a blank object, a person who's name is empty? It has no way of knowing this, and instead of taking the decision in it's own hands and, thereby confusing you later on when you find an unexpected item in the array.

Reference types don't normally have any default value other than null, and the compiler has no way of knowing what kind of default you want to use, so it lets you tell it what to do.

This also has added benefits because it prevents your program from allocating more space than it needs to store this new array and it has to keep track of less objects in the array to see if they need to be garbage collected.

The best example of this would be if you have the following, both Person and Baby are valid types, the compiler, if it did decide to fill the array with what it considered to be a default, how would it chose between the two?

Baby[] babies = new Baby[]
{
    new Baby(),
    new Person()
};

public class Baby
{

}

public class Person : Baby
{

}
DekuDesu
  • 2,224
  • 1
  • 5
  • 19
1

Array declaration basically allocates the memory required to store the object in a continuous way. Every variable will be initialized with its default value.

So in your case, Person is a reference type and the default value is null. Whereas considering the array as like below

int[] arr = new int[3];

Each item in the array will have zero as its value.

Kumaran
  • 65
  • 9
1

Perhaps an analogy would help to explain the concept. This applies to arrays which store reference type objects, such as the one in your question. (Value type arrays behave slightly differently, as one of the other answers has already discussed).

Imagine you have an empty space on the wall in your house. You plan to buy some books about a particular subject, and you need somewhere to store them. So you decide to create a bookshelf with enough space to hold 20 such books.

Once you have built the bookshelf, the shelf is ready, but there are no books on it. You cannot take or use a book from it. But then you can add books one at a time, or in groups, and then you can take them, read them, swap them, remove them etc.

Your array is empty at first because it is like the bookshelf - it's a place to store the objects, but it does not contain any objects unless you specifically put them there. You need to create an object (equivalent to buying a book) and then put it into the array (equivalent to placing it on the shelf). The shelf does not know exactly which books you intend to store on it, and there is no such thing as a "standard" or "default" book which it can place there in advance of the real ones.

ADyson
  • 57,178
  • 14
  • 51
  • 63
0

Just to add on that, there is a neat syntax to initialize arrays in declaration itself, that you might find useful:

var arr = new[] { new Person("Joe"), new Person("Pam") };
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36