When you allocate an array the runtime zeros the memory - fullstop.
So for reference types you get an array of null references and for value types (structs) you get an array of zeroed value types. This is the reason behind why you cannot declare a custom *default* constructor on a value type - if you did the runtime would have to execute it as many times as there are members of the array - which could be a significant hidden overhead in array allocation.
Also, when you write the code
MyStruct[] s = new MyStruct[100];
s[23] = new MyStruct(40, 2);
the second line is not creating anything, its simply re-initializing an already allocated block of memory. So while, in theory, running the contructor as part of array allocation using the (made up) syntax
MyStruct[] s = new MyStruct[100](40, 2); // REPEAT: I HAVE JUST INVENTED THIS SYNTAX
causes the constructor to run 100 times - so does the following.
MyStruct[] s = new MyStruct[100];
for( int i = 0; i < s.Length; i++ )
{
s[i] = new MyStruct(40, 2);
}
And internally the runtime would have to loop over each piece of memory to run the constructor as well, so there is no real difference between the two - except that the cost is very obvious in the latter example whereas it is less obvious in the first.
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog http://www.dotnetconsult.co.uk
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway,
although Ollie's answer makes perfectly sense when dealing with
classes, it doesn't seem to me to apply as well if you have to
instantiate an array of structures; consider the following useless
code :