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
.