Small Lists issue
im trying to check if a list remained the same after a prozess:
''' List<string> startList=previousList;
previousList.Add("item");
Console.Writeline(startList==previousList);
'''
This, according to me, should output false since the list was changed. However for some reason the "startList" is also changed simultaniously with the "previousList", eventhough I didn't use ".Add()" with "startList". Why does this happen and how can I fix it?
3 Replies
they point to the same list
This is a general programming thing. Your assignment of
var startList = previousList;
only copies the reference to previousList
to startList
. Both variables will still refer to the same instance of the list.
What you need to do is copy the list. You can do that via var startList = new List<string>(previousList);
.
Beyond that, you cannot check list equality by using ==
. Lists are reference types and don't implement a custom equality operator, meaning you're simply comparing whether the two variables refer to the same instance. What you need is something like startList.SequenceEquals(previousList)
.Thank you very much. This helped a lot. Everything works correctly know.