c# - Initialize a byte array to a certain value, other than the default null? -


this question has answer here:

i'm busy rewriting old project done in c++, c#.

my task rewrite program functions close original possible.

during bunch of file-handling previous developer wrote program creates structure containing ton of fields correspond set format file has written in, work done me.

these fields byte arrays. c++ code use memset set entire structure spaces characters (0x20). 1 line of code. easy.

this important utility file goes expecting file in format. i've had change struct class in c#, cannot find way initialize each of these byte arrays space characters.

what i've ended having in class constructor:

//initialize of variables spaces. int index = 0; foreach (byte b in usercode) {     usercode[index] = 0x20;     index++; } 

this works fine, i'm sure there must simpler way this. when array set usercode = new byte[6] in constructor byte array gets automatically initialized default null values. there no way can make become spaces upon declaration, when call class' constructor initialized straight away this? or memset-like function?

for small arrays use array initialisation syntax:

var sevenitems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }; 

for larger arrays use standard for loop. readable , efficient way it:

var seventhousanditems = new byte[7000]; (int = 0; < seventhousanditems.length; i++) {     seventhousanditems[i] = 0x20; } 

of course, if need lot create helper method keep code concise:

byte[] sevenitems = createspecialbytearray(7); byte[] seventhousanditems = createspecialbytearray(7000);  // ...  public static byte[] createspecialbytearray(int length) {     var arr = new byte[length];     (int = 0; < arr.length; i++)     {         arr[i] = 0x20;     }     return arr; } 

Comments