"using" blocks are often written like this:
using (new Foo()) { ... }
rather than like this:
using (var f = new Foo()) { ... }
In the first case, where no explicit reference to the new Foo object is set, is there any danger that the object could be disposed prior to the end of the block? If not, why not?
There is no danger that it will be disposed early.
The first example still creates an explicit reference to the object that is created. That reference is just unnamed and can't be used in your code.
The using
block will hold the reference (albeit unnamed) until the end of the block.
No you don't need to set an explicit reference, unless you need to access the object with the scope block. There is no danger of the unreferenced variable being disposed early because it is only disposed of when it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With