I instantiate an array like this:
int array[] = new int[4];
What are the default values for those four members? Is it null, 0 or not exists?
I instantiate an array like this:
int array[] = new int[4];
What are the default values for those four members? Is it null, 0 or not exists?
The default value of an automatically-initialized variable of type
T
, such as an array element or an instance field, is the same as the value ofdefault(T)
. For reference types and pointer types, it's null. For numeric types, it is the zero of that type. For bool, it's false. For struct types, it is the struct value that has all its fields initialized to their default values.Integers cannot be
NULL
. They will have the value '0'. Even if you try to assignNULL
to aint
from code you will not be able to do it.It's 0. It can't be null, as null isn't a valid
int
value.From section 7.6.10.4 of the C# 5 specification:
And from section 5.2:
(As an implementation detail, there's some trickiness around the first bullet point. Although C# itself doesn't allow you to declare a parameterless constructor for value types, you can create your own parameterless constructors for value types in IL. I don't believe those constructors are called in array initialization, but they will be called in a
new X()
expression in C#. It's outside the realm of the C# spec though, really.)From Arrays (C# Programming Guide):