Reputation: 34750
byte[] bytes = new byte[100];
bytes.Initialize();
What's the default values in above bytes
byte array after the Initialize() called? all null\0?
Upvotes: 2
Views: 536
Reputation: 284786
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.
Upvotes: 5
Reputation: 137128
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 0
s.
(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.
Upvotes: 3
Reputation: 113242
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.
Upvotes: 2