I know this has been discussed many times but no solutions seems to work so I thought and may be worth a try to reopen it since some time has passed.
I have a function:
Public Function Test() As Object
Dim retVal As DisposableObject
Dim tempRetVal As DisposableObject
Try
tempRetVal = New DisposableObject
retVal = tempRetVal
tempRetVal = Nothing
Return retVal
Catch
tempRetVal.Dispose()
Throw
Finally
tempRetVal.Dispose()
End Try
End Function
As you can see, there are a lot of Dispose statements. This is because I was trying to find a way to have it working. The only way I found (which clearly is not a solution) was to add retVal.Dispose() before returning retval.
Public Function Test() As Object
Dim retVal As DisposableObject
Dim tempRetVal As DisposableObject
Try
tempRetVal = New DisposableObject
retVal = tempRetVal
tempRetVal = Nothing
retVal.Dispose()
Return retVal
Catch
tempRetVal.Dispose()
Throw
Finally
tempRetVal.Dispose()
End Try
End Function
Any hint will be gladly appreciated! :)
Note: I'm using VS2012
EDIT: I also tried the simple template proposed by MS and it doesn't work either:
Public Function Test() As Object
Dim retVal As DisposableObject
Dim tempRetVal As DisposableObject
Try
tempRetVal = New DisposableObject
retVal = tempRetVal
tempRetVal = Nothing
Return retVal
Finally
if tempRetVal isnot Nothing then tempRetVal.Dispose()
End Try
End Function
CA2000 is thrown on tempRetVal = New DisposableObject.
Why? You anyways have a
finallyblock defined. Let the finally block take care of the disposal. Your code should look like below. Also,See CA2000: Dispose objects before losing scope for more information.
EDIT:
To my believe, you are getting that CA2000 warning message because of the
returnstatement insideTRYblock. Rather,returnthe obejct before your subroutine actually end. See below code with comment added to the changes. This will be fine now.