This is a question I was asked at my interview recently: Which 'Random' object(s) would get collected during the 'GC.Collect()' call?
String a = new Random().Next(0, 1) ==1 ? "Whatever 1" : "Whatever 2";
String b = new WeakReference(new Random()).Target.Next(0, 1) == 1 ?
"Whatever 1" : "Whatever 2";
GC.Collect();
I answered that this is an implementation-specific question and it highly depends on the GC
implementation and the corresponding weak reference semantics. As far as I know, C# specification doesn't provide exact description of what GC.Collect
should do and how should the weak references be handled.
However, my interviewer wanted to hear something else.