When a List<> of primitive types is created in C# (e.g. a List<int>), are the elements inside the list stored by value, or are they stored by reference?
In other words, is C# List<int> equivalent to C++ std::vector<int> or to C++ std::vector<shared_ptr<int>>?
A
List<int>will have anint[]internally. No boxing is required usually – the values are stored directly in the array. Of course if you choose to use theList<T>as a non-genericIList, where the API is defined in terms ofobject, that will box:Note that the phrase “stored by reference” is a confusing one – the term “by reference” is usually used in the context of parameter passing where it’s somewhat different.
So while a
List<string>(for example) contains an array where each element value is a reference, in aList<int>each element value is simply anint. The only references involved are the callers reference to theList<int>, and the internal reference to the array. (Array types themselves are always reference types, even if the element type is a value type.)