52

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

5 Answers 5

114
Byte[] array = new Byte[64];

Array.Clear(array, 0, array.Length);
Sign up to request clarification or add additional context in comments.

3 Comments

It won't be optimized out of the Release build though, right? Eg: SecureZeroMemory vs ZeroMemory in Win32.
@c00000fd Please check this answer
What is the performance difference between the two methods? When would I use one over the other?
25

Kindly use Array.Empty method

byte[] rawBytes = Array.Empty();

2 Comments

byte[] rawBytes = Array.Empty<byte>();
@sbr This has been helpful since I needed to pass it to a method in tests. Thanks!!
7

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];

Comments

3

Use the "clear" method on Array.

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

Comments

1
for (int i = 0; i < array.Length; i++)
    array[i] = 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.