1
Obj[] array = new Obj[10];

What's the default value for each object in this array? I want them all to be null and I'm not sure if there's a need to set each of them to null in a loop.

Michael Yochpaz
  • 187
  • 1
  • 4
  • 15

4 Answers4

7

Yes, the online documentation says so:

The default values of numeric array elements are set to zero, and reference elements are set to null.

The C# specification (Section 1.8 Arrays) is even more specific:

The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

This highly depends on the type of object Obj is. If it is a reference type then the values are null. If it is a value type then the value is not null.

More general the values of the array are initialized to the value returned by default(ObjClass) respectivly default(ObjStruct) or generally default(anyTypeHere)

Example

class Program
{
    static void Main()
    {
        ObjStruct[] array = new ObjStruct[10];
        Console.WriteLine(array[0].Test);
    
        ObjClass[] array = new ObjClass[10];
        Console.WriteLine(array[0].Test); //NullReferenceException
    }
}

public class ObjClass
{
    public string Test { get { return "Not null"; } }
}

public struct ObjStruct
{
    public string Test { get { return "Not null"; } }
}
Community
  • 1
  • 1
Michael Mairegger
  • 6,833
  • 28
  • 41
0

Each array element is initialized with default value of the type default(T).

If it is a reference type then is null, if it is a value type then is 0 for types like int, long, double, and in the case of struct fields are initialized to their default values.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
0

by default it will be null. you can see more explanation here if you will use extended types https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

avis
  • 19
  • 1
  • 7