Inappropriate List <long> Property Behavior
public class Foo { public static List<long> myList = new List<long>() { 1,2,3 } } In another method:
var testList = Foo.myList; If I put a breakpoint on the last line and check testList , it changes different lengths from time to time.
When I use ToList() on Foo.myList , it works correctly. But why?
Edit:
My problem was that I again called an ajax call> modified Foo.myList > a new ajax call> Foo.myList and got the changed value.
The race condition is in general condition. A static member of a field means one copy, so if you manipulate the list in your code, it changes for ALL threads using the property. ToList() works because it creates a copy of the list that will not modify the original list, but note that this copy also points to the same objects as the original list if the objects are reference types . Therefore, changing reference types in a copy would also change the values โโin the original list ... but since long is a value type that is not applicable here.
If you want your list to be read-only http://msdn.microsoft.com/en-us/library/e78dcd75.aspx
It looks like you are modifying Foo.myList or a link to it somewhere. Note that assigning a list to a local variable does not create a copy. In this way:
var list = new List<long> { 1, 2, 3 }; var testList = list; testList.Add(4); // list is now [1, 2, 3, 4] list.Add(5); // testList is now [1, 2, 3, 4, 5] ToList (), on the other hand, creates a copy. In general, it is probably safe to do only read-only static lists (if the semantics you want) so that this doesn't happen by accident:
public class Foo { // pre .NET 4.5, use ReadOnlyCollection<T> (which implements IList<T>) public static readonly IReadOnlyList<long> myList = new List<long> { 1, 2, 3 }.AsReadOnly(); } var testList = Foo.myList.ToList(); // get an editable copy var testList2 = Foo.myList; // get a reference to the immutable static list