tags:

views:

74

answers:

3
byte[] bytes = new byte[100];
bytes.Initialize();

What's the default values in above bytes byte array after the Initialize() called? all null\0?

+5  A: 

The method docs note that it initializes value types to default-constructed values, but not if they are built-in. Thus, the method is a no-op in this case. However, it will already be set to 0 after the array is created, since you haven't provided an initializer (see tutorial). In general, you probably don't want to use this method. From the docs,

"This method is designed to help compilers support value-type arrays; most users do not need this method. It must not be used on reference-type arrays."

If you want to set it to 0, you couldn't use this method (since byte is built-in). Instead, you would use a for loop or (if performance is important) something like Buffer.BlockCopy.

C# will never let you read uninitialized memory, except in unsafe mode.

Matthew Flaschen
The default constructor is not the same as `default(T)` so the docs you link to do not agree with what you say.
Jon Hanna
@Jon, thanks, I've corrected it.
Matthew Flaschen
+3  A: 

Well according to the documentation:

Initializes every element of the value-type Array by calling the default constructor of the value type.

So in this case it you would think that it calls the default constructor of the type byte, the result of which would be an array filled with 0s.

(This MSDN page shows the default values of value types returned by the default constructors.)

However, on the same page there is this note of caution though:

You can use this method only on value types that have constructors; however, value types that are native to C# do not have constructors.

Which means that in this case it does nothing as byte is a value type native to C# and hence doesn't have a constructor.

ChrisF
Your "note of caution" points out that what you say above is wrong.
Jon Hanna
@Jon - Thanks, I knew that there was something bothering me about that!
ChrisF
+2  A: 

It has no effect.

byte[] test = new byte[100];
test[1] = 4;
test.Initialize();
Console.WriteLine(test[1]);

will print 4. The effect of Initialize is not (as may perhaps have been more sensible) to return default(T) but to call new T(). In cases where this does not work, it fails silently.

Jon Hanna
Quote: "You can use this method only on value types that have constructors; however, value types that are native to C# do not have constructors." I only know of C++/CLI as a language that supports value types like this.
Hans Passant
C# Does support value types with default constructors, but only allows you to explicitly set other constructors, the default can only be the type it has by default (the "default default constructor" I suppose...)
Jon Hanna