Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incosistent behaviour of List<long> property

Tags:

c#

asp.net

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.

like image 446
Johan Avatar asked Dec 20 '22 03:12

Johan


1 Answers

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

like image 191
Haney Avatar answered Dec 26 '22 20:12

Haney