Search code examples
asp.netvb.netobjectcode-behindmultiple-instances

Removing multiple instances a an object prior to exiting a subroutine


I have a few questions on the usage of the "New" keyword and removing multiple instances of an object.

If a subroutine in a code-behind ASP.Net statement like this is executed each time the subroutine is executed, will there be many instances of employeeDetails.DataKeyNames? This object is local to the subroutine.

employeeDetails.DataKeyNames = New String() {"EmployeeID"} 

If the answer is yes, should I use code to remove all copies of employeeDetails.DataKeyNames when the subroutine containing this code is finished? In that case please show what coding is required to remove all copies of employeeDetails.DataKeyNames hanging around.


Solution

  • The New in this case will replace whatever exists in the .DataKeyNames property with the new value. In this case, you aren't adding more values to that property, but will see a performance penalty of repeatedly creating and destroying the string arrays. It is better to check to see if the value was set and then not replace it with a simple if clause:

    If employeeDetails.DataKeyNames Is Nothing Then
      employeeDetails.DataKeyNames = New String() {"EmployeeID"}
    End If
    

    That being said, you may want to check the other logic in your code to determine why you are calling into this method repeatedly and see if there are ways of reducing those calls.