Assuming I have a method public static Rectangle DrawRectangle(Vector origin, Vector size) which returns an object of type Rectangle : IDisposable
If I call only the method DrawRectangle(origin, size), but do not assign the return value to a variable myRectangle = DrawRectangle(origin, size), will the compiler automatically detect this and call DrawRectangle(origin, size).Dispose(), or do I have to do it myself?
There are only two scenarios I can think of where the compiler automatically calls dispose; the most obvious would be:
which is an explicit instruction to say “at the end, whether success or failure, if
objis non-null, callobj.Dispose()“. Basically it expands to:The other is
foreach, where-by the iterator is disposed – although it gets a bit complicated, becauseIEnumeratordoesn’t specify thatIDisposableis required (by contrast,IEnumerator<T>does specify that), and technicallyIEnumerableis not even required forforeach, but basically:could be expressed as (although the spec may say it slightly differently):
In all other cases, disposing resources is your responsibility.
If you don’t ensure that
Dispose()is called, then nothing will happen until GC eventually collects the object; if there is a finalizer (there doesn’t have to be, and usually isn’t), the finalizer will be invoked – but that is different toDispose(). It may (depending on the per-type implementation) end up doing the same thing asDispose(): but it may not.