Reputation: 13
List<int[]> three_number_sums = new List<int[]>();
int[] _3Ints_arr = { 2, 6, 9 };
three_number_sums.Add(_3Ints_arr); // storing array in List as 2,6,9
_3Ints_arr[0] = 1;
_3Ints_arr[1] = 10;
_3Ints_arr[2] = 100; // array now is 1,10,100
if(!three_number_sums.Contains(_3Ints_arr)) // does not exist
three_number_sums.Add(_3Ints_arr);
I wonder why my program under the if
statement still treats as exists even after overriding _3Ints_arr
with 1,10,100?
This same concept works (if
treated as not exists) for List of strings however once "apple" is overridden by "orange" in the string:
List <string> words = new List <string> ();
string word = "apple";
words.Add(word); // storing word in List as "apple"
word = "orange"; // string now is "orange"
if (!words.Contains(word)) // does not exist
words.Add(word);
Upvotes: 1
Views: 44
Reputation: 116
In the first example, the list contains the reference to the array _3Ints_arr
.
When you change the content of this array, the reference to the array doesn't change and three_number_sums.Contains(_3Ints_arr)
returns true
.
In the second example you are using string
, which is immutable: when you assign a new value to word
, word
is no more the reference you had added to the list.
So words.Contains(word)
is false
.
Upvotes: 2