If I've got this class defined as part of an app in ASP.NET 2.0:
public class Foo
{
private static int _seed = 100;
private static object myLock = new object();
public Foo()
{
lock (myLock)
{
this.MyInt = _seed;
_seed++;
}
}
public int MyInt {get; set;}
}
(Edit: updated to account for thread safety concerns as pointed out by answers)
How will that static member behave? Will it start at 100 and increment separately for every session, or will it increment separately for every page refresh, or is it global...?
Note: I'm asking this because I'm using classes to model data for the first time in my ASP.NET app, and I've already discovered that C#'s by-reference nature appears to be ignored by ViewState serialization, so I want to know what other weirdness I can expect. For example, if I have this class defined (assume Bar is another class):
public class OtherFoo
{
public List<Bar> Bars {get; set;}
}
and I do this on my page:
OtherFoo _myFoo = new OtherFoo();
//Code here to instantiate the list member and add some instances of Bar
Bar b = _myFoo.Bars[0];
ViewState["myFoo"] = _myFoo; //Assume both are [Serializable]
ViewState["myBar"] = b;
When I get those out of ViewState on the next postback, b and _myFoo.Bars[0] are no longer the same object.