Static Object, Global Variable, Lazy Loading in C#


The static attributes in a class are served as global variables. A static variable can be accessed directly by class. You don’t need the instances (of class) in order to access static attributes (e.g. in C#, you can define static class that contains only static methods). All instances of the same class share the same copy of the static variables.

In Java, you can initialize static objects in static block, something like this:

public class Sample {
  public static Object obj;
  static {
    obj = new Object();
  }
}

The static block is invoked once, when the class is loaded. It is the same as:

public class Sample {
  public static Object obj = new Object();
}

In C#, you can do exactly the same, so when the class is first loaded, the object is created. However, if the object is not frequently used, you might want to delay the creation to whenever needed. So, in C#, you can have the following lazy loading:

public class Sample {
  private static Object _obj;
  public static Obj {
    get {
      if (_obj == null) {
         lock(_obj) {
             if (_obj == null) {
                 _obj = new Object();
             }
         }
      }
      return _obj;
    }
  }
}

We declare a private attribute _obj and at the get method of public attribute Obj we first check if it is null. Please note that it is likely that many threads will access the attribute at the same time, so we have to lock it before one of the thread has to created it for the first time. Then after the object has been created, we need to place a check for other threads just in case they are waiting at the lock.

The lock is time consuming and that is why we put a outmost check to avoid locking after the first time object is created. The read operations do not require locking the objects.

–EOF (The Ultimate Computing & Technology Blog) —

377 words
Last Post: Run as Administrator in VBScript/JScript (WSH)
Next Post: Restart Apache Web Server On Errors

The Permanent URL is: Static Object, Global Variable, Lazy Loading in C# (AMP Version)

Leave a Reply