Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Lifespan static members

I found this code in the system I'm working on:

public class Foo
{
  private static HashTable Bar = new HashTable();

  public static void AddData(SomeObject obj)
  {
      Bar.Add(obj.Key, obj);
  }

  // lots of stuff removed
}

Now i'm not sure about the lifetime of this static HashTable. It gets created the first time AddData is called but when is it destroyed? Does the framework keep objects with static members alive indefinitely (that is the end of the process) or are they at risk of being GC-ed earlier, let's say after x period of non usage. (in which case, the code sucks).
I can't find any specs on this on MSDN or elsewhere.

Thanks in advance

Geert-Jan Thomas
Monday, January 03, 2005

A Static member's lifespan is the length of the application or server. So, for example, if you had an object with a counter as part of an ASP.NET application that counter would remain until either the dll is replaced or the server is shutdown.

Cory Foy (cornetdesign.com)
Monday, January 03, 2005

Also, the Hashtable doesn't get created the first time the method gets called, it is always available. To have it not be created until the first call you'd have to do a Lazy Load like:

public class Foo
{
  private static Hashtable Bar = null;

  public static void AddData(SomeObject obj)
  {
      if(Bar == null)
      {
          Bar = new Hashtable();
      }

      Bar.Add(obj.Key, obj);
  }
}

Cory Foy (cornetdesign.com)
Monday, January 03, 2005

Actually, it does get created when the method is first called. Sorta.

It's created in the static constructor, and the static constructor isn't called until the first reference to a static method or member is referenced.

Brad Wilson
Monday, January 03, 2005

Brad,

So because it is being created in the static contructor I guess it would be created on *any* call to that class, not just one useing the Hashtable?

Cory Foy (cornetdesign.com)
Monday, January 03, 2005

It's all documented here, in detail: http://www.yoda.arachsys.com/csharp/singleton.html

John Rusk
Monday, January 03, 2005

Thanks a lot folks!
I still think it's a awkward way of caching but hey! if it works!
I'll go with it.

Geert-Jan Thomas
Monday, January 03, 2005

*  Recent Topics

*  Fog Creek Home