0

Given the C# code below, I expected the private data member _userDataStorage to be initialized immediately. Instead I find that it is not being initialized at all. I put a breakpoint on the initialization statement and it is never hit. This means the DB static property always returns NULL. Do static classes work differently than non-static classes?

public static class UserDataStorageWrapper
{
    private static UserDataStorage _userDataStorage = new UserDataStorage();

    public static UserDataStorage DB
    { 
        get
        {
            return _userDataStorage;
        }
    }
}

I will change the code to check for NULL and initialize _userDataStorage myself for now. But I want be sure about my expectations here.

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227
  • 2
    Is your property actually returning `null`, or is your breakpoint simply not being hit? – Brian S Feb 27 '14 at 20:24
  • Do you see anything different when you use a static constructor to initialize the value? – JG in SD Feb 27 '14 at 20:27
  • 4
    Do you actually use the class? It might not be initialized unless it's being used. – Chris Feb 27 '14 at 20:28
  • It's definitely returning null and the breakpoint is not hit, that's why it's returning null, because the initializer is not being executed. Looking at MAV's answer it looks like static initializer's aren't fired unless the object is accessed. Since it's private that never happens. Kind of strange policy IMHO. – Robert Oschler Feb 28 '14 at 01:52

2 Answers2

6

Since it is a static initializer it will be initialized "at an implementation-dependent time prior to the first use of a static field of that class". Source

So your breakpoint might not get hit unless you use that field (or another static field in that class).


For completeness I can add that if there is a static constructor, the static field initializers will be executed before the static constructor.

MAV
  • 7,260
  • 4
  • 30
  • 47
0

Try adding a static constructor and initialize the variable inside.

public static class UserDataStorageWrapper
{
    public static UserDataStorageWrapper()
    {
        _userDataStorage = new UserDataStorage();
    }

    private static UserDataStorage _userDataStorage;

    public static UserDataStorage DB
    { 
        get
        {
            return _userDataStorage;
        }
    }
}

"If a static constructor exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor" source

Alejandro del Río
  • 3,966
  • 3
  • 33
  • 31