Sunday 15 May 2011

vb.net - CA2000: Dispose objects before losing scope -


When I try to run code analysis in my project I am getting errors in this part of the code.

// code

  Try as private sub SaveMaterialStatus (ByVal situation is not as) Dim cSMaterialInput cSMaterialInput = some string then ViewState ( "CSInput ") isnot nothing then 'Create a new transaction cSMaterialInput = end new cSMaterialInput cSMaterialInput = ViewState (" CSInput ") cSMaterialInput.CSStatus = position CSMaterialInputMethods.SaveToDatabase (cSMaterialInput, Environment.UserName, Environment.MachineName) catch prior exception If you throw at the end then cSMaterialInput isnot is nothing, then try cSMaterialInput.Dispose () from the other end. Sub   

Detailed error:

  CA2000 method 'ShowSummary.SaveMaterialStatus (string) throw before losing scope of' objects, on System.IDisposable.Dispose object Call out of scope 'cSMaterialInput' before all references xxxx.CostingTool.Presentation ShowSummary.aspx.vb 790   

where am I wrong ??

  cSMaterialInput = new CSMaterialInput   

This is the place Where the problem started. You can immediately reassign the variable in the next statement, so that the object you have created can never be settled. Which triggered the CA2000 warning, there is no point in creating a new object that you have never used. Which leaves a bit more in the method:

  Private Sub SaveMaterialStatus (ByVal status as string) dim cSMaterialInput = ViewState ("CSInput") if cSMaterialInput isNot nothing cmsaterialInput.CSStatus = position CSMaterialInputMethods.SaveToDatabase (cSMaterialInput, Environment.UserName, Environment.MachineName) end if end Sub   

with nothing tests still an important code smell. It's just hiding a bug when your program tries to save anything .

1 comment: