Static methods are not objects that are subject to garbage collection, so
they have no lifetime issues for you to deal with.
For each static field there is one copy per-appdomain - each appdomain can
have a different value. The static variable itself is not garbage
collected - it is just a memory location that contains a reference to an
object. Static fields are considered to be GC roots, so any references in
them will not be garbage collected as long as the field contains that
reference. If you change the field to point to a new reference or set the
field value to null then the object whose reference was stored there becomes
eligible for collection.
Static class constructors will run once for each appdomain they get loaded
in.
Per your example, the method AddItem() is not an object that can get
garbage collected, it is a method. Each time you call AddItem a new
Collection object will be allocated and its reference assigned to the field
coll. Any previous reference stored in that field will be eligible for
garbage collection, but the current reference will not be GCd.
"Chuck Cobb" <ch********@oxf ordcorp.com> wrote in message
news:OJ******** ******@TK2MSFTN GP05.phx.gbl...
I am creating some static classes with static methods and static variables,
but I have a question: What is the lifetime of static classes and static
variables? Is there any risk that these items might be garbage collected
if they're not used for a period of time?
For example:
public static class test
{
static Collection<stri ng> coll;
public static void AddItem()
{
coll = new Collection<stri ng>();
coll.Add("abc") ;
}
public static string GetItem(int index)
{
return coll[index];
}
}
Suppose I call the AddItem method and nothing is holding a reference to
this class, what's to prevent it from being garbage collected and
destroyed?
Do static members like this live for the life of the application without
being subject to garbage collection?
Thanks,
Chuck Cobb