consider below code
class Repository{
public static Item i; //Item is a type (class)
GetItem(){
// initialize i if null. Read i from an xml file if the last write time of file is greater than last read time else return current i
return i;
}
SaveItem(item){
//save i;
//write i to xml file
i=item;
}
}
class User{
public static void Main(){
Repository r = new Repository();
r.GetItem().MakeChangesToItem(); //method inside item to make some changes
r.SaveItem(r.GetItem());
}
}
Is there any chance this code behaves sporadically. Apparently it does for me. Sometimes the changes are reflected in the static item sometime not. When i changed the Main method code to
Item i=new Repository().GetItem();
i.MakeChangesToItem();
r.SaveItem(i);
it works normally.
Has any one experienced this? Thanks
Static means it is not tied to any instance, but is per-type instead. A common issue with static is threading. If you have multiple threads (for example, an ASP.NET or WCF application, or anything where you use threads/tasks/parallel yourself) then craziness can ensue as they all think they’re talking about different things, overwriting the same field.
I would say static is very unsuitable for that field.