Lazy <T> in the eyes of GC?
I was wondering: how the GC
object seesLazy
i.e.
Lazy<Foo> f = new Lazy<Foo>( );
"Lazy Instantiation" defers the creation of an object until it is actually accessed
Is the f
root for the object? (which means it won't be GC'ed)?
(the object is not created at this point ... some other code will put the value into it later)
or
GC treats it as an unreferenced / uninitialized object and GCe'd.
Is this something I need to take care of? (/fear?)
public class Foo
{
public int ID { get; set; }
public Foo()
{
ID = 1;
}
}
source to share
f
is indeed a reference to an instance Lazy<Foo>
. The encapsulated instance Foo
is separate, but is made (maintained) indirectly available.
While it exists f
, i.e. it is rooted or reachable, an instance will not (cannot) be built.
There is nothing special about GC here. Don't confuse Lazy with WeakReference.
source to share