Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object eligible for garbage collection if it's created within using-statement and not explicitly bound to a reference?

I have this (illustration only) C# code:

using( new System.IO.MemoryStream() ) {
    System.Threading.Thread.Sleep(1000);
}

Note that here a MemoryStream is created and not explicitly bound to a reference. So unless there's some special treatment because of the using statement the object has no references to it and could be collected before control leaves the using statement and maybe even before Sleep() completes.

Is MemoryStream eligible for collection before control leaves the using statement?

like image 873
sharptooth Avatar asked Dec 20 '22 06:12

sharptooth


2 Answers

No.

The using statement compiles to a finally block that disposes the object.

Thus, it is still in scope until the end of the block.

like image 75
SLaks Avatar answered Feb 12 '23 10:02

SLaks


No, it is NOT.

Behind the scenes, a hidden reference to the MemoryStream has been created, so it is still alive.

like image 24
Matthew Watson Avatar answered Feb 12 '23 12:02

Matthew Watson