What is the benefit of or reason for using this pattern?..
public sealed class myStaticClass
{
private static bool _initialized;
private static object _lockObject;
private static string _someStaticField;
private static int _anotherStaticField;
private static string _nthStaticField;
static myStaticClass()
{
_initialized = false;
_lockObject = new object();
}
public myStaticClass()
{
}
public static void Initialize()
{
if(!_initialized)
{
lock(_lockObject)
{
if(!_initialized)
{
//do initializing
_someStaticField = someApplicationSetting;
_anotherStaticField = anotherApplicationSetting;
_nthStaticField = nthApplicationSetting;
_initialized = true;
}
}
}
}
public static string NthStaticField
{
get {
Initialize();
return _nthOtherField;
}
}
}
If a static constructor is guarenteed to be called before any of the class members are ever accessed and it is only ever called once then why not just put all of the initialization logic in the static constructor?
EDIT: I have updated the pattern to better reflect the class in the .net framework where I have discovered it. I have change the static
modifier on the class to sealed
and I have also added an empty public
constructor.
ps. Incase you would like to know, the class where I have seen this pattern is the FormsAuthentication
class.
The only reason to do so would be if initialization is expensive (in terms of CPU/RAM) OR something needed is only available later during runtime IMO... this implementation delays initialization until the latest possible moment (right before first access). It is kind of what Lazy<T>
offers...
Possibly, the ApplicationSettings are not available until later on during run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With