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 at the last line and inspect testList
it gives me different lengths from time to time.
When I use ToList()
on Foo.myList
it seems to behave correctly. But why?
Edit:
My problem was that I made an ajax call > modified Foo.myList
> new ajax call > fetched Foo.myList
again and got the modified value.
Race condition on shared state. The static field member means there's 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 which won't alter 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 altering the reference types in the copy would also alter the values in the original list... but since long
is a value type that won't apply here.
If you want your list to be read-only http://msdn.microsoft.com/en-us/library/e78dcd75.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With