I am doing some practice test questions and one of them is as follows:
You are creating a class named Data that includes a dictionary object named _data. You need to allow the garbage collection process to collect the references of the _data object. How should you complete the relevant code?
public class Data
{
<replace1>
public Data(int count)
{
for (int i = 0; i < count; i++)
{
<replace2>
}
}
}
Here are the options:
static Dictionary<int, WeakReference> _data;
static Dictionary<int, Int32> _data;
_data.Add(i, new WeakReference(new Class(i*2), false));
_data.Add(i, (Int32)(i*2));
Since, basically, the question is "Should you use a WeakReference or a struct reference if you want the Garbage Collector to be able to collect your objects?" I thought the Int32 struct would be a better choice, since it references no object on the heap and thus the object can be garbage collected immediately, even though weak references do not keep an object alive if there are no strong references to it (as far as I understood it) I still thought the struct would be a better answer but the practice test says the WeakReference is the correct answer. Mind you this practice test has been wrong before even for the most obvious and simple matters.
Could you explain why, in this case, a WeakReference would be better suited than a struct if we want the GC to be able to collect our object?
AppDomain-widestaticobjects - MickyWeakReferenceis? That achieves the same result with less uncertainty. I don't like answering questions when it looks like they haven't been thought out, and I realize that they might have the answer to their own question wrong based on factors they haven't considered. Or all of the answers are wrong and you have to guess which one they thought was right, and why. And to really split hairs, neither dictionary is instantiated. - Scott Hannenstatic- J. Doe