Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Cost of not disposing isn't really high enough to be worth such code-obfuscating contortions.

The garbage collector makes sure objects are properly disposed of. The only real cost to letting the collector handle it is that the object ends up surviving for an extra GC cycle. It's sloppy practice, and it means memory consumption will be higher if your program rapidly generates a lot of short-lived IDisposables, but otherwise the difference will probably be trivial.



I'm not saying to avoid IDisposable (just the opposite in fact).

The `foreach` statement and the `using` statement just so happen to desugar to similar code when it comes to handling IDisposable. The C# compiler will guarantee that Dispose() is called on the iterator and that code in the `finally` block will execute... even if you exit the loop early due to an `exception` or a break/goto. Just like the `using` statement.

The benefit is that it's even more of a pit-of-success feature than the `using` statement because you can't possibly forget to call Dispose().

It's also only slightly more work for the library author and slightly less work for the client but the client is going to use the code many more times than the author will write it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: