The question is: why do we need to call Dispose() on some objects? Why doesn’t the garbage collector collect the object when it goes out of scope? I am trying to understand the reason why it was implemented like that. I mean, wouldn’t it be easier if Dispose() was called when the garbage collector collected out of scope objects.
The question is: why do we need to call Dispose() on some objects? Why
Share
The garbage collector is non-deterministic – it collects objects at some point after they’re no longer referenced, but it’s not guaranteed to happen in a timely fashion. This has various benefits over reference counting, including allowing cyclic dependencies and the performance benefit of not incrementing and decrementing counters all over the place.
However, it does mean that for resources which should be cleaned up in a timely manner (such as database connections, file handles etc – almost anything other than memory) you still need to explicitly dispose of the resource. The
usingstatement makes this pretty easy though.