Static private data member not initialized in static class?
-
24-12-2019 - |
Question
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.
Solution
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
OTHER TIPS
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.