V3225. A data reading method returns the number of bytes that were read and cannot return the value of -1.

The analyzer has detected a possible incorrect check of the method's return value. Some methods return values that indicate successful execution. Developers may expect the method to return -1, but it actually returns 0.

The example:

public void ProcessStream(Stream s)
{
  byte[] bytes = new byte[s.Length + 10];
  int numBytesRead = 0;
  int n = s.Read(bytes, numBytesRead, 1);
    
  if (n == -1)
  {
    ....
  }

  ....
}

In this case, the check of the method's return value is redundant because the Read method returns 0 at the end of the stream.

The fixed code:

public void ProcessStream(Stream s)
{
  byte[] bytes = new byte[s.Length + 10];
  int numBytesRead = 0;
  int n = s.Read(bytes, numBytesRead, 1);
    
  if (n == 0)
  {
    ....
  }

  ....
}

This diagnostic is classified as: