Lifetime of the object

In some block creates an anonymous object and the object in the "weak link":

//first object System.Random
string result = new Random().Next(0,1) == 1 ?
  "equal 1":"sory, but not equal 1";

//second object System.Random 
string result = ((Random)new WeakReference(new Random()).Target).Next(0,1) == 1 ?
  "equal 1":"sory, but not equal 1";

GC.Collect();

Which of comments tagged objects has a greater chance to stay alive after the garbage collection?

Jon Skeet
people
quotationmark

Well in the second example, it's hypothetically possible for the Random instance to be immediately collected after the WeakReference constructor completes and before the Target property is accessed - there's no strong reference to it at that point, after all. So the second code is broken anyway, IMO.

In both cases, the System.Random object is eligible for garbage collection as soon as the GC can detect that nothing will access any of its data any more - so probably just before the end of the Next() method call. Additionally, the WeakReference object is eligible for garbage collection in the second case, immediately after the use of the Target property.

"Greater chance to stay alive" isn't a precisely defined concept here - as noted in Servy's comments, an object is or isn't eligible for garbage collection. Within certain implementations one could reason about what's most likely to happen, but doing so would usually be a bad idea given that implementation details can and do change.

people

See more on this question at Stackoverflow