I wrote the code in data access layer method -
Public Shared Function GetDetails(ByVal strEmpName As String) As DataSet Dim dsResult As DataSet = New DataSet() Try ' my code for constructing the command and dataadapter 'da' da.Fill(dsResult) Catch ex As Exception Finally ' some cleanup End Try Return dsResult End Function
Simple but when I compile was getting the warning message - 'CA2000 : Microsoft.Reliability : In method 'GetDetails(String)', call System.IDisposable.Dispose on object 'dsResult' before all references to it are out of scope. xyz.vb'Without clearing this warning I can not check in. refer 'http://msdn.microsoft.com/en-us/library/ms182289.aspx'. Cause - 'A local object of a IDisposable type is created but the object is not disposed before all references to the object are out of scope.' The idea behind the CA2000 rule is to free memory when scope is ended. But what about the object which we need to return to the calling method. While writing code make sure not to initialize the IDisposable objects; and create/allocate only when returning, so that the method returns the object with proper data only when executed successfully. In other cases (like exception or no data) return Nothing (null in C#) so that the memory is used effectivily.
For the solution I modified to initialize the DataSet to 'Nothing'
Public Shared Function GetDetails(ByVal strEmpName As String) As DataSet Dim dsResult As DataSet = Nothing Try ' my code for constructing the command and dataadapter 'da' da.Fill(dsResult) Catch ex As Exception Finally ' some cleanup End Try Return dsResult End Function
If Not dsResult Is Nothing Then 'bind to grid End If
No comments:
Post a Comment