0

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?!

8
  • 2
    Try to post your code here instead of printing the image!! Commented Aug 14, 2013 at 18:12
  • At least what "line 210" is, is very obvious :P Commented Aug 14, 2013 at 18:13
  • How do you know size1 has a value of 160? Commented Aug 14, 2013 at 18:14
  • 2
    The image also shows the values of local variables during runtime. As it is the runtime behavior that I want to illustrate, the image is appropriate. Also, no one is likely to believe me when I say byte[] buf = new byte[size1] results in buf having 2 bytes despite size1 has a value of 160! The image of runtime behaviors makes my case. Commented Aug 14, 2013 at 18:18
  • The image would be appropriate if you include some sample source code that we can copy into our own IDEs and try it for ourselves. Commented Aug 14, 2013 at 18:20

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly! Can't believe I commit a classic newbie mistake, which is the values of the local variables as shown in the debug window are the state of the program at the point the program stops/breaks, not some arbitrary lines before the break point. I still have to figure out the problem with b.ReadBytes(...) but at least I will be going down the correct alley. Thanks Scott!
4

ReadBytes() returns a byte[]. When you write

buf = b.ReadBytes(Marshal.SizeOf(firstRecord));

then buf points at a completely different byte[] that equals whatever b.ReadBytes() returned.

Comments

0

It looks like you're trying to convert some object into a byte array, this answer may help. Convert any object to a byte[]

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.