Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When using calling the SqlCommand.ExecuteReader() method, ReSharper tells me I have a possible NullReference exception when I use the SqlDataReader object afterwards.

So with the following code:

using (SqlConnection connection = GetConnection())
{
    using (SqlCommand cmd = connection.CreateCommand())
    {
        cmd.CommandText = ; //snip

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                //snip
            }
        }
    }
}

The while (reader.Read()) line is underlined.

My question is when would the reader object ever be null? I've never come across it and the documentation doesn't mention that it could be. Should I be checking if it's null or is it safe to ignore?

And why would ReSharper think that it could be null, when for example it lets me use the SqlCommand without recommending it be checked for null? I'm guess there's an attribute on the ExecuteReader method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
465 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's a false positive.

Reflecting on SqlDataReader.ExecuteReader, I can see that the only way the reader is returned as null is if the internal RunExecuteReader method is passed 'false' for returnStream, which it isn't.

In the depths of SqlDataReader, a reader constructor is always called at some point, so I'm pretty sure this is not physically possible for ExecuteReader to return null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...