Question

MyClass[] CLASS = new MyClass[5];
int[] STRUCT = new int[5];

What exactly is new [] doing for a class vs a struct. Apparently the struct has some overloaded static index that causes it to run the default constructor of the struct. However the new [] for a class appears to do nothing but make space to initialize an instance of a class. How do I overload the static behavior of the class to also run the default constructor. I know how to use for loops and other methods of accomplishing this. My question is very specific to what is going on underneath the new []. I understand that a struct needs a default value. But doesn't a non-nullable class also need a default value which is why it gives an error when you try to use it? Or is this telling me that all classes are actually nullable?

Was it helpful?

Solution

No, the default constructor of struct isn't run. What happens instead is that in the struct case, the memory is initialized to zero. What this means depends on the data type. E.g., a reference field (like a class or a string) becomes null, numeric fields become 0, boolean fields become false, etc.

This differs very much from how classes work. This is why with the initialization of the class array, you see null values. Basically, it comes down to this. An "empty" class variable (or array in your case) becomes null. However, when you have an "empty" struct, you already have something valid. However, it is initialized as empty.

The easiest way to see this is when you e.g. have an int field in a class. This works basically the same way. When you add an int field to a class, you are not required to initialize it. When you don't initialize it, it gets the value 0 by default. struct's work the same way in this regard.

See http://msdn.microsoft.com/en-us/library/aa664471.aspx for a bit more information.

A few more things to note (answer to the question in the comments):

  • Classes are always nullable. This means that the only way to initialize the array is to create a loop and initialize a new instance for every item in the array;
  • The default constructor doesn't apply to structs, because they aren't allowed to have a default constructor. If you try to compile the following code snippet, you will get a compilation error telling you this:

    struct MyStruct
    {
        public MyStruct()
        {
        }
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top