views:

46

answers:

1

When I write:

var tagType = _reader.ReadByte();

while (tagType != 8)
{
    var skip = ReadNext3Bytes() + 11;
    _reader.BaseStream.Position += skip;

    tagType = _reader.ReadByte();
}

...it's working, but when I write:

var tagType = _reader.ReadByte();

while (tagType != 8)
{
    _reader.BaseStream.Position += ReadNext3Bytes() + 11; 
     tagType = _reader.ReadByte();
}

...it is not working, and I can't understand why - I'm getting unexpected results. Heres the ReadNext3Bytes method:

    private long ReadNext3Bytes()
    {
        try
        {
            return Math.Abs((_reader.ReadByte() & 0xFF) * 256 * 256 + (_reader.ReadByte() & 0xFF) 
                * 256 + (_reader.ReadByte() & 0xFF));
        }
        catch 
        {
            return 0;
        }
    }

Why is that, and how can I fix it?

Thanks.

+2  A: 

It happens since Position is changed during ReadByte call, what you see is similar to this case:

int position = 1;
position += (position = 2) + 3;

Assert.AreEqual(6, position);
Elisha
Oh!!!!! Thanks!
TTT
.NET stores the value of Position before it starts evaluating the right side of the assignment, best way is the simplest one: the first form you wrote that worked. The second way, which I like less is to reduce 3 from the increment expression: _reader.BaseStream.Position += ReadNext3Bytes() + 11 - 3;
Elisha