>
>
>
V3095. The object was used before it wa…


V3095. The object was used before it was verified against null. Check lines: N1, N2.

The analyzer has detected a potential error that may cause access by a null reference.

The analyzer has noticed the following situation in the code: an object is being used first and only then it is checked whether this is a null reference. It means one of the following things:

1) An error occurs if the object is equal to null.

2) The program works correctly, since the object is never equal to null. The check is not necessary in this case.

Let's consider the first case. There is an error.

obj = Foo();
result = obj.Func();
if (obj == null) return -1;

If the 'obj' object is equal to null, the 'obj.Func()' expression will cause an error. The analyzer will generate a warning for this code mentioning 2 lines: the first line is the place where the object is used; the second line is the place where the object is compared to null.

This is the correct code:

obj = Foo();
if (obj == null) return -1;
result = obj.Func();

Let's consider the second case. There is no error.

Stream stream = CreateStream();
while (stream.CanRead)
{
  ....
}
if (stream != null)
  stream.Close();

This code is always correct. Stream object is never equal to null. But the analyzer does not understand this situation and generates a warning. To make it disappear, you should remove the check "if (stream != null)". It has no sense and can only confuse a programmer while reading this code.

This is the correct code:

Stream stream = CreateStream();
while (stream.CanRead)
{
  ....
}
stream.Close();

When the analyzer is wrong, you may use (apart from changing the code) a comment to suppress warnings. For example: "obj.Foo(); //-V3095".

This diagnostic is classified as:

You can look at examples of errors detected by the V3095 diagnostic.