Why converting List to Array not referencing in c#?

Viewed 135

An array in .Net is a reference type. Given the two code segments above. Question: why setting value varible "fixedItem" affects varible "data" in the first segment code, but the second segment code is does not affects

First code segment:

        var data = new List<IList<int>>();
        data.Add(new List<int>() { 1, 2, 3 });
        data.Add(new List<int>() { 3, 8, 6,5 });
        data.Add(new List<int>() { 1, 2 });
        var fixedItem = data.Last();
        fixedItem[1] = 8;
        
        //Result:
        //data = {{1,2,3}, {3,8,6,5}, {1,8}}

Second code segment:

        var data = new List<IList<int>>();
        data.Add(new List<int>() { 1, 2, 3 });
        data.Add(new List<int>() { 3, 8, 6,5 });
        data.Add(new List<int>() { 1, 2 });
        var fixedItem = data.Last().ToArray();
        fixedItem[1] = 8;
          
        //Result:
        //data = {{1,2,3}, {3,8,6,5}, {1,2}}
5 Answers

docs

according to documentation list.ToArray() method returns array with copies of original list

With the first version, fixedItem is the last item from the outer list, i.e. the third inner list. The same instance. Changing that list will be visible everywhere that list is referenced.

However, in the second version you use ToArray(), which creates a separate copy of the list contents, in a vector. You can do anything you like with your isolated copy - it is a different collection instance (and different collection type). Changing it will only be visible to things that reference the copy. The original list is unaffected because it is a different collection.

This is because with ToArray method, you have created a copy of the original list.

Official documentation

Copies the elements of the List to a new array.

There are many thing involve over here.

  1. When you do ToArray in second segment , it actually create new variable and new collection.

  2. Here you have created list of int, in this integer is value type so when it create new collection it copies those value and assign new memory location.

  3. Now instead of int if you have created some reference type like object of class then if you change value over in one collection affect other. Here variable is new but it still reference the same memory location.

Look at the data types you've created after using Last() from Linq. You receive two very different data types.

One would be a list while the other is just int[]. They have fairly different functionalities and ways to represent and handle data.

Related