-2

I am using below menioned code for Inserting Data into SQL and for that I have used below menioned code

 public void ExecuteSQLCommandWithParameters(string command,params object[] Values)
    {
        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
        conn.ConnectionString = _connectionString;


        try
        {
            conn.Open();

            System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(command, conn);
            for (int i = 0; i < Values.Length; i++)
            {
                com.Parameters.Add("@"+i.ToString(), Values[i]);
            }

            com.ExecuteNonQuery();
            com.Dispose();
            conn.Close();
            Values = null;


        }
        catch (Exception ex)
        {
            log.Error(string.Format("Error in ExecuteSQLCommand(), command {0}, exception: {1}", command, ex.Message));
        }
    }

The above mentioned function will Execute A Thousand Times my question is is it required to make NULL params object[] Values I means Do I need to write code like

Values=null;

Please suggest me

Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
  • No. Garbage Collector will do it for you. –  Aug 12 '14 at 09:31
  • 4
    Can't hurt to stick that connection in a using block though! – Liath Aug 12 '14 at 09:32
  • @pwas Garbage collection will do no such thing. Garbage collection will do what the OP hopes to accomplish by setting it to null, but what the OP hopes to accomplish is already not done by that assignment. –  Aug 12 '14 at 09:33
  • If you set object to `null` then you're extending the life of the object upto that statement. If you don't, it can be garbage collected at the point where your code doesn't reference it. – Sriram Sakthivel Aug 12 '14 at 09:37

1 Answers1

3

No it is not necessary. The reference to the array (which is what Values contains) will be on the stack and therefore thrown away at the end of the method automatically.

The actual array that Values points to will be removed when the garbage collector runs and realises nobody is using it any more. That is, when there are no more references to it from live objects.

Paolo
  • 22,188
  • 6
  • 42
  • 49