I'm trying to find an answer to a seemingly straightforward question,
but it is proving more difficult than I thought it would.

The question is: if I create an array of pointers, using unsafe code in
C#, will the elements of the array all be initialized to null?

The documentation in the C# spec initially seems clear: section 12.2
'Array creation' says that elements of arrays created by
array-creation-expressions are always initialized to their default
value.  But section 5.2 'Default values' only defines the default values
for value types and reference types.

Section A.2 'Pointer types' makes it clear that pointer-type is
different from either value-type or reference-type, so the information
in 5.2 presumably doesn't apply here, since it only talks about
pointer-type and reference-type.  I can't actually find anything that
says what the default value for a pointer-type would be.

So the provisional conclusion I reached from the C# spec is that if I
create an array of pointers, the value of the elements is undefined
(because there is no definition that tells us what the default value for
a pointer-type is). So if I want the array to start off full of nulls,
I'm actually going to have to loop through and fill it with nulls.

This seems kind of surprising, since you don't normally have to
initialize arrays.  But I guess in an unsafe context, fewer things are
guaranteed for you.


Moreover, Serge Lidin's "Inside Microsoft .NET IL Assembler" says of the
'newarr' instruction that the newly created array is always
zero-initialized. It doesn't mention any exceptions. (At least not on
any of the pages listed for 'newarr' in the index...)

Partition III of the CLI spec is a little less clear. In section 4.19,
it says that when newarr is used to create a zero-based one-dimensional
array of numbers, that the elements of the array will be initialized to
0.  It also says that non-zero-based or multi-dimensional arrays don't
use newarr. Unfortunately it doesn't say what happens with zero-based
one-dimensional arrays of anything other than numbers, which is a shame,
since the C# compiler uses newarr when creating a new array of pointers.


Empirically, I get all nulls when creating a new array of pointers.  But
my reading of the specs indicates that this is not something that I can
rely on, because the official behaviour appears to be undefined.

Did I miss anything in the documentation that clears this up?


-- 
Ian Griffiths
DevelopMentor

===================================
This list is hosted by DevelopMentorŪ  http://www.develop.com
NEW! ASP.NET courses you may be interested in:

2 Days of ASP.NET, 29 Sept 2003, in Redmond
http://www.develop.com/courses/2daspdotnet

Guerrilla ASP.NET, 13 Oct 2003, in Boston
http://www.develop.com/courses/gaspdotnet

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to