Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static class "Initialize" pattern in C#?

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.

like image 593
Duncan Gravill Avatar asked Mar 16 '12 22:03

Duncan Gravill


2 Answers

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...

like image 63
Yahia Avatar answered Sep 29 '22 10:09

Yahia


Possibly, the ApplicationSettings are not available until later on during run-time.

like image 28
torrential coding Avatar answered Sep 29 '22 08:09

torrential coding