Search code examples
c#arraysresizedefault-value

In C# resizing an array (increasing its size in this case) initializes the new segment with default values – is this reliable?


In C# resizing an array (increasing its size in this case) initializes the new segment with default values – is this reliable?

Array.Resize(ref bytes, bytes.Length + extra);

I do see the default values (0 for byte arrays), but is it possible to safely take that as the standard behavior for all base types? In my application saving every second is a big deal, hence thought I could avoid unnecessary loop to initialize the newly added segment if it is already available by default. Microsoft .NET document doesn’t explicitly state this fact: https://learn.microsoft.com/en-us/dotnet/api/system.array.resize?view=netframework-4.8 although the examples kind of hint to that behavior.


Solution

  • Yes, you can rely on that. From the documentation (emphasis mine):

    This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. array must be a one-dimensional array.

    Allocating a new array is guaranteed to populate it with default values (effectively "set all bits to 0"), so if we trust the description, the result of the overall Array.Resize operation would indeed have default values for all elements which haven't been copied from the old array.