-1

So, I am coding it as below,

sqlcommand.connection.close(); sqlcommand = null;

Now, Visual Studio is giving me a warning as it is an unnecessary assignment at sqlcommand = null. Kindly suggest.

5
  • If Visual Studio tells this, it will likely be true. You can check this by simply setting a breakpoint and having a look. If you still need help, please be more precise and add your source code. Commented Apr 21, 2022 at 9:07
  • Can you please show broader context of the code in question? If assigning to null is the last thing you do before sqlcommand goes out of scope the assignment is indeed redundant - the object will be garbage collected nevertheless. Commented Apr 21, 2022 at 9:17
  • I am more curious to know if we explicitly need to set SQL command as null after we perform close() or not Commented Apr 21, 2022 at 9:18
  • In C# - no, the moment reference goes out of scope it'll be garbage collected. In C# garbage collector checks if there exist living reference to an object in addition to reference counting. Commented Apr 21, 2022 at 9:20
  • Does that Mean I'll have to call Dispose() after close()? Commented Apr 21, 2022 at 9:23

1 Answer 1

3

If you dont want to care about closing of connections and disposing these objects - best practice should be using

using (SqlConnection myConnection = new SqlConnection(connectionString))
{
    myConnection.Open();
    using (SqlCommand myCommand = new SqlCommand(command, myConnection))
    {
               
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the input. I know Using statement can sort this out for me. But I am more curious to know if we need to set SQL command as null after we perform close().
Or even using var myConnection = new SqlConnection(connectionString); without {...}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.