tags:

views:

26

answers:

3

Hi,

I would like to implement an current property in my class which returns the current active context of the class (much like httpcontext.current etc.), like so:

using(classA x = new classA(..))
{
    classB.Dosomething();
}

where the method dosomething() gets the current context of classA to perform some operation.

How would i go about creating such functionality?

Greetz, Richard

A: 

Obviously it would need some concurrency protection but if you are looking for the singleton way.... (it would also need to implement IDisposable)

public class A {
    public static A Current { get { return _instance } }

     private static A _instance {
         get 
         { 
            if(_instance ==null){ 
                 instance = new A();
             } 
             return _instance;
          }
      }

}

Nix
A: 

Usually, a "Current" property is a static property kept on a per-thread basis. ThreadLocal<T> is ideal for implementing this.

Stephen Cleary
This would be an option if your are using c# 4.0.
Richard
A: 

You should make a [ThreadStatic] static Current property, then write Current = this in the constructor, and set it to null in Dispose. You might want to throw an exception if someone makes a second copy in the same thread. Alternatively, you could maintain a stack.

SLaks
This is the one for me, as i'm not using c# 4.0. Thanx a bunch.
Richard