Search code examples
asp.netstaticstatic-variablesstatic-class

Are static variables inside static classes unique to the class?


I created some static utility methods that I use for caching objects.

public static class CacheProductView
{
    static object _lock = new object();
    static string _key = "product-view";

    public static IEnumerable<Product> Select()
    {
        var obj = CacheObject;

        if (obj == null)
        {
            lock (_lock)
            {
                obj = CacheObject;

                if (obj == null)
                {
                    obj = CreateCacheObject();
                }
            }
        }
    }

}

Here's a snippet of code from the method I use. As you can see, I use the classic .Net caching pattern, however I have a question regarding static variables inside static classes.

Is the static variable unique within the static class? For instance, if I clone the class and replace 'Product' for 'Order', will the _lock and _key objects, be scoped to the class or the application. Obviously, if the answer is the latter, giving unique names would be be needed.

All help and advice appreciated.


Solution

  • Answering your question - static fields and properties are defined per type.

    Great article about what goes where in types and instances
    http://www.codeproject.com/Articles/20481/NET-Type-Internals-From-a-Microsoft-CLR-Perspecti

    Besides that - pattern you present is not a good way to go.