In the following code, if cmd has been initialized, then I'll make to sure to close any open connections before throwing an exception. However, even after I check that cmd is not null, I still get a possible null reference warning in subsequent lines of code.
Dim cmd As SqlCommand
Try
'Do some Stuff
Catch ex As Exception
If cmd IsNot Nothing AndAlso
cmd.Connection IsNot Nothing AndAlso '<- null cmd warning
cmd.Connection.State = ConnectionState.Open Then '<- null cmd warning
cmd.Connection.Close() '<- null cmd warning
End If
Throw
End Try
I get the two following warnings (possibly one from Resharper & one from Visual Studio):
- Variable 'x' might not be initialized before accessing. A null reference exception could occur at runtime.
- BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
According to the Visual Studio Page:
An application has at least one possible path through its code that reads a variable before any value is assigned to it.
But I don't think there is even one possible path through the code where the variable would be used without being initialized.
- Have I made some error or is this a bug?
- Is there a way to disable this warning from coming up?
Here's a screenshot:

This is different from many similar questions already asked here, like Prevent Resharper “Possible Null Reference Exception” warnings because I'm not trying to allow for a NullableType, but instead have already guaranteed that my variable is not null.
Update:
Follow up question: Why?
Whether my object is never initialized or initialized to Nothing, in both cases cmd IsNot Nothing should resolve to False, so anything after the AndAlso should never be executed.
Dim cmd1 As SqlCommand
Console.Write(cmd1 IsNot Nothing) 'False
Dim cmd2 As SqlCommand = Nothing
Console.Write(cmd2 IsNot Nothing) 'False
Maybe the compiler just doesn't have a good way of guaranteeing this at compile time.