Do containers of primitive types in C # use value semantics or pointer / reference semantics?

When List<>primitive types (for example, a List<int>) are created in C # , are the items in 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 C ++ std::vector<shared_ptr<int>>?

+3
source share
3 answers

A List<int>will have int[]internally. Usually no boxing is required - the values ​​are stored directly in the array. Of course, if you decide to use it List<T>as non-generic IList, where the API is defined in terms object, this will be a field:

List<int> list1 = new List<int>();

// No boxing or unboxing here
list1.Add(5);
int x = list1[0];

// Perfectly valid - but best avoided
IList list2 = new List<int>();

// Boxed by the caller, then unboxed internally in the implementation
list2.Add(5);

// Boxed in the implementation, then unboxed by the caller
int y = (int) list2[0];

, " " : " " , .

, a List<string> () , , List<int> - int. List<int> . ( , .)

+6

. (, ). . (, )

0

, , :

struct MutableValueType
{
  public int ChangableInt32;
}

static class Program
{
  static void Main()
  {
     var li = new List<MutableValueType>();
     li.Add(new MutableValueType());
     li[0].ChangableInt32 = 42;
  }
}

Will you change the copy of your structure or change the copy inside List<>? Will the compiler warn you? I'd like to try that.

0
source

All Articles