kilianvde
kilianvde

Reputation: 35

C# Code explanation

i've this piece of code from an open source c# program.

I'm trying to figure out the purpose behind this snippet.

internal static bool ReadAsDirectoryEntry(BinaryReader br)
    {
        bool dir;

        br.BaseStream.Seek(8, SeekOrigin.Current);
        dir = br.ReadInt32() < 0;
        br.BaseStream.Seek(-12, SeekOrigin.Current);

        return dir;
    }

The code on LINE 6 is unclear to me , can anyone explain what it does ? How can a bool have a value of the returned int32 and smaller than zero ?

Thanks!

Upvotes: 0

Views: 223

Answers (4)

Mehmet Ataş
Mehmet Ataş

Reputation: 11549

internal static bool ReadAsDirectoryEntry(BinaryReader br)
{
    bool dir;

    // Skip 8 bytes starting from current position
    br.BaseStream.Seek(8, SeekOrigin.Current);

    // Read next bytes as an Int32 which requires 32 bits (4 bytes) to be read 
    // Store whether or not this integer value is less then zero
    // Possibly it is a flag which holds some information like if it is a directory entry or not
    dir = br.ReadInt32() < 0;

    // Till here, we read 12 bytes from stream. 8 for skipping + 4 for Int32
    // So reset stream position to where it was before this method has called
    br.BaseStream.Seek(-12, SeekOrigin.Current);

    return dir;
}

Upvotes: 2

Damien
Damien

Reputation: 8987

The line 6 means : read an Int32 then compare it to 0 and then store the comparison result into a Boolean.

It's equivalent as :

Int32 tmp = br.ReadInt32();
dir =  tmp < 0;

Upvotes: 0

user2674389
user2674389

Reputation: 1143

You read an int and check if this int is smaller than 0. The expression br.ReadInt32() < 0 will result in a bool. This bool result you assign to your variable.

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062590

basically, that is logically equivalent to (but terser than):

bool dir;
int tmp = br.ReadInt32();
if(tmp < 0)
{
    dir = true;
}
else
{
    dir = false;
}

It:

  • does the call to ReadInt32() (which will result in an int)
  • tests whether the result of that is < 0 (which will result in either true or false)
  • and assigns that result (true or false) to dir

To basically, it will return true if and only if the call to ReadInt32() gives a negative number.

Upvotes: 1

Related Questions