I was wondering about : How GC sees the Lazy object
i.e. :
Lazy<Foo> f = new Lazy<Foo>( );
“Lazy Instantiation” defers creation of an object till the time it is actually accessed
Does f here is a root for the object ? ( meaning he wont be GC’ed ) ?
( the object is not created by this time… some other code put a value in it later on)
or
GC sees it as un-referenced / un-initialized object – and GCe’d it.
Is it something which I need to take care of ? ( / fear of ?)
public class Foo
{
public int ID { get; set; }
public Foo()
{
ID = 1;
}
}
fis indeed a reference to theLazy<Foo>instance. The encapsulatedFooinstance is separate but is made (kept) reachable indirectly.As long as
fexists, ie it is a root or it is reachable, the instance won’t be (can’t be) collected.There is really nothing special regarding GC here. Don’t confuse Lazy with WeakReference.