Search code examples
c#serializationallocation

C# byte array doesn't allocate correctly


Screenshot of weird problem

I'm trying to serialize an object in C#. I got the object size and saved it in a variable, size1 on line 207 in above screenshot. Size1 has a value of 160. Then I used size1 to allocate an array of bytes called buf in line 210. Buf comes out to be a 2 byte array! How can this be?!


Solution

  • The problem is here

    byte[] buf = new byte[size1];
    byte[] buf2 = new byte[16];
    buf = b.ReadBytes(...); //<----
    

    You are replacing buf with the result of ReadBytes. That throws away your original array and replaces it with the array that was returned from ReadBytes (which in your case was a two byte array)