5
public class MyClass<T>
{
    public static readonly String MyStringValue;

    static MyClass()
    {
        MyStringValue = GenerateString();
    }

    private static String GenerateString()
    {
        //Dynamically generated ONCE per type (hence, not const)
    }

    public void Foo()
    {
        Console.WriteLine(MyStringValue);
    }
}

It's my understanding that the static readonly String won't get generated until the static constructor is called on the class. But, the static constructor won't be called until one of the static methods or variables is accessed.

In a multi-threaded environment is it possible to run into issues because of this? Basically, is the static constructor by default singleton locked or do I have to do this myself? That is... do I have to do the following:

private static Object MyLock;

static MyClass()
{
    lock(MyLock)
    {
        if (MyStringValue == null)
            MyStringValue = GenerateString();
    }
}
michael
  • 14,844
  • 28
  • 89
  • 177
  • possible duplicate of [Is the C# static constructor thread safe?](http://stackoverflow.com/questions/7095/is-the-c-static-constructor-thread-safe) – Adam Sills Jun 16 '11 at 19:53

2 Answers2

8

The static constructor is guaranteed to run only once per instantiated type. So you don't need your locking.

Note that it will run once for each generic parameter. And the static fields on the generic class aren't shared between different generic parameters either.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

To avoid this why not make the value a static property with only a get accessor which returned the cached value, which you could then make private? Accessing the property get would assure the static constructor ran first.

Ed Bayiates
  • 11,060
  • 4
  • 43
  • 62