3 ms·
Well, there are certainly cases where you grab a reference speculatively; anything where you need > N in a collection to act on, for instance, but don't know ho
by kmontrose 15y ago
Well, there are certainly cases where you grab a reference speculatively; anything where you need > N in a collection to act on, for instance, but don't know how many items there are yet (such as when you're reading from a stream). There's also the "early return" case, where you'd grab reference say A, B, and C but only dereference C in code that runs if A and B failed some condition.
The equivalent to timely destruction in C# is a using statement combined with implementing IDisposable.
using(var stream = File.Open(somePath))
{
// use stream to do whatever
}
This is syntactic sugar for a try{ } finally { } (that also exists in Java) that calls Dispose() in finally. You do any cleanup you need to in Dispose(), things like releasing file handles. The only way to dodge that Dispose() is to tear the execution thread down, which generally means the process is gone with it.
C# classes (but not structs) can also declare destructors, but their execution schedule isn't guaranteed; they're useful for making absolutely sure resources are released eventually, Dispose() is preferred for timing and performance.