Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to set an explicit reference to a new'd object in a using block?

Tags:

c#

"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?

like image 224
Jan Hettich Avatar asked Jan 03 '11 20:01

Jan Hettich


2 Answers

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.

like image 100
Justin Niessner Avatar answered Nov 15 '22 04:11

Justin Niessner


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.

like image 22
BlackICE Avatar answered Nov 15 '22 06:11

BlackICE