Suppose I have some simple struct
like this:
public struct WeightedInt {
public int value;
public double weight;
}
Then let's say I have a collection of instances of this structure:
List<WeightedInt> weightedInts = new List<WeightedInt>();
As I understand value types versus reference types, value types are allocated on the stack, so a value type object is cleared from memory once the function instantiating said object terminates. This means that in the following code:
void AddWeightedIntToList(int value, double weight) {
WeightedInt wint = new WeightedInt();
wint.value = value;
wint.weight = weight;
weightedInts.Add(wint);
}
a copy of the local variable wint
is added to weightedInts
whereas the local variable itself is removed from memory after AddWeightedIntToList
is completed.
First of all: is this correct?
Secondly, where does this copy of wint
get stored? It can't be on the stack, since then it would be gone once the function completed (right?). Does this mean that the copy is stored on the heap along with weightedInts
? And is it garbage collected after being removed, as if it were an instance of a reference type?
It's certainly possible that this question is answered in an article somewhere, in which case, a link to that article would be a totally acceptable answer. I just haven't had any luck finding it.