Empty elements in C# byte array

109,234

Solution 1

Byte[] array = new Byte[64];

Array.Clear(array, 0, array.Length);

Solution 2

Kindly use Array.Empty method

byte[] rawBytes = Array.Empty();

Solution 3

I tried endlessly to use Array.Clear() to clear a large byte[] that I have in my program. It would NEVER work. I do not know why. But I found a solution:

array = new byte[0];

Solution 4

Use the "clear" method on Array.

 Array.Clear(array , 0, array.Length);

Solution 5

for (int i = 0; i < array.Length; i++)
    array[i] = 0;
Share:
109,234
leon22
Author by

leon22

Updated on July 09, 2022

Comments

  • leon22
    leon22 almost 2 years

    Is there any method to empty an Byte array in C#?

    Byte[] array = new Byte[64]; // contain all 0
    
    // write some value into the array
    
    // need empty array with all 0's
    
  • c00000fd
    c00000fd almost 7 years
    It won't be optimized out of the Release build though, right? Eg: SecureZeroMemory vs ZeroMemory in Win32.
  • sbr
    sbr over 3 years
    byte[] rawBytes = Array.Empty<byte>();
  • MartinZ
    MartinZ about 3 years
    @c00000fd Please check this answer
  • Zapnologica
    Zapnologica about 3 years
    What is the performance difference between the two methods? When would I use one over the other?
  • badjuice
    badjuice over 2 years
    @sbr This has been helpful since I needed to pass it to a method in tests. Thanks!!