Initialize a byte array to a certain value, other than the default null? [duplicate]
For small arrays use array initialisation syntax:
var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
For larger arrays use a standard for
loop. This is the most readable and efficient way to do it:
var sevenThousandItems = new byte[7000];for (int i = 0; i < sevenThousandItems.Length; i++){ sevenThousandItems[i] = 0x20;}
Of course, if you need to do this a lot then you could create a helper method to help keep your code concise:
byte[] sevenItems = CreateSpecialByteArray(7);byte[] sevenThousandItems = CreateSpecialByteArray(7000);// ...public static byte[] CreateSpecialByteArray(int length){ var arr = new byte[length]; for (int i = 0; i < arr.Length; i++) { arr[i] = 0x20; } return arr;}
Use this to create the array in the first place:
byte[] array = Enumerable.Repeat((byte)0x20, <number of elements>).ToArray();
Replace <number of elements>
with the desired array size.
You can use Enumerable.Repeat()
Enumerable.Repeat
generates a sequence that contains one repeated value.
Array of 100 items initialized to 0x20
:
byte[] arr1 = Enumerable.Repeat((byte)0x20,100).ToArray();