-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.

  • 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. – Jonas Metzler Apr 21 '22 at 09: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](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#928-local-variables) the assignment is indeed redundant - the object will be [garbage collected](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#memory-release) nevertheless. – orhtej2 Apr 21 '22 at 09:17
  • I am more curious to know if we explicitly need to set SQL command as null after we perform close() or not – Shashikant Tantarpale Apr 21 '22 at 09: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. – orhtej2 Apr 21 '22 at 09:20
  • Does that Mean I'll have to call Dispose() after close()? – Shashikant Tantarpale Apr 21 '22 at 09:23

1 Answers1

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))
    {
               
    }
}
fubo
  • 44,811
  • 17
  • 103
  • 137