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
{
}