3 ms·
Is it the same as try with resources in Java? try(var reader = getReader()) { // do read } // auto-close
by ivan_gammel 1y ago
Is it the same as try with resources in Java?
try(var reader = getReader()) {
// do read
} // auto-close
- masklinn 1y agoIt's similar, but more inspired by C#'s "using declaration", an evolution of the using blocks, which are the C# version of try-with-resource: `using` declarations don't introduce their own block / scope. The original proposal references all of Python's context manager, Java's try-with-resource, and C#'s using statement and declaration: https://github.com/tc39/proposal-explicit-resource-management?tab=readme-ov-file#prior-art https://github.com/tc39/proposal-explicit-resource-managemen...
- OskarS 1y agoOnly experience with C# using and Python context managers, but they always seemed like such an unsatisfying solution compared to C++/Rust style RAII. I mean, I get these are GC languages, but why can't just this happen at end of your regular scope? Why do you have to have these artificial new scopes?
- neonsunset 1y agousing var stream = GetStream(); does not introduce new (lexical) scope, avoiding use means that the type system either has to understand move semantics (in case the stream is returned or move elsewhere, but then, what about sharing?) or have full-blown borrow checker which will emit drop.
- maxfurman 1y agoThat's what's neat about the simpler C# version (and this proposal): it's bound to whatever block it's in and doesn't need its own scope/indentation
- mattmanser 1y agoYeah, as someone else has pointed out it's C# inspired, this is a C# example: public void AMethod() { //some code using var stream = thing.GetStream(); //some other code var x = thing.ReadToEnd(); //file will be automatically disposed as this is the last time file is used //some more code not using file } //any error means file will be disposed if initialized You can still do the wrap if you need more fine grained control, or do anything else in the finally. You can even nest them like this: using var conn = new SqlConnection(connString); using var cmd = new SqlCommand(cmd); conn.Open(); cmd.ExecuteSql(); Edit: hadn't read the whole article, the javascript version is pretty good!