4 ms·
IMO the big benefit of 'using' statements is that they have the ability to incorporate RAII-type semantics (the idea of scoped resource lifetimes) into C#, whic
by maximilianburke 15y ago
IMO the big benefit of 'using' statements is that they have the ability to incorporate RAII-type semantics (the idea of scoped resource lifetimes) into C#, which normally doesn't have them, via objects that implement the IDisposable interface. It can make it cleaner and less error-prone to have the language perform cleanup for you automatically than relying on the user to do so himself.
- politician 15y agoAnother strong use-case involves database transactions (TransactionScope).
- noblethrasher 15y agoAS I argued elsewhere[1], exploiting the way C# handles `foreach` is a better way of achieving RAII IMHO; it forces the client code to do the right thing rather than hoping it will remember to use the `using` statement (or manually call Dispose()). [1]http://news.ycombinator.com/item?id=3423426 http://news.ycombinator.com/item?id=3423426
- bunderbunder 15y agoCost 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.
- noblethrasher 15y agoI'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.