Basically, why does this work?
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
When this doesn't:
System.IO.Stream stream = new MemoryStream();
int a = 3;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
This is the error I get:
The offset and length were greater than allowed for the matrix, or the number is greater than the number of elements from the index to the end of the source collection.
When using Marshel.SizeOf(a)
you ask the size of the object in memory. Since a
is an int
the size is always 4.
When you say byte[] barray = new byte[a];
you say:
Create an array called barray
of type byte
with length a
. Thus in the first code block you create an array of length 4 and in the second one you create an array of length 3. Both array's contain only zero's.
Then you say: write the (empty) array to the stream, starting at position 0 and with length 4 (Marshel.SizeOf(a)
is always 4 because a
is an int).
The first example array has a length of 4 and thus works. The second example only contains 3 bytes and thus the length is not correct and you get an error.
If you wish to save the int to the stream as bytes explicitly you could call BitConverter
:
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = System.BitConverter.GetBytes(a);
stream.Write(barray, 0, Marshal.SizeOf(a));
Now you say: create an array called barray
that is filled with the binary representation of integer variable a
.
And then write that filled array to the stream.