Static string variable with complex initialization in C #

I have a class with a static string variable that has somewhat complicated initialization (I cannot just set it equal to the quoted string, for example "whatever"). I need to run a few lines of code in order to actually create a value. Once it is installed, its value will not change. It is currently configured as a property that is simply set on the first call get.

class MyClass
{
    private static string _myString = "";
    public static string MyString
    {
        get
        {
            if(_myString == "")
            {
                // use an object "obj" here to create the value
                MyObject obj = new MyObject();
                obj.someSetupHere();
                _myString = obj.ToString();
            }
            return _myString;
        }
    }
}

My question is: is there a better way to do this? I would prefer that the value be set when all other variables are set, and not on the first "get" value. Should I use here Lazy<T>? I would really like:

private static string _myString = 
{
        // use an object "obj" here to create the value
        MyObject obj = new MyObject();
        obj.someSetupHere();
        _myString = obj.ToString();
}

, , , , , , , .

+4
1

:

private static readonly string _myString = GetMyStringValue();

private static string GetMyStringValue()
{
    MyObject obj = new MyObject();
    obj.someSetupHere();
    return obj.ToString();
}

, Func<string>, :

private static readonly string _myString = ((Func<string>) () =>
{
    MyObject obj = new MyObject();
    obj.someSetupHere();
    return obj.ToString();
}).Invoke();

:

private static readonly string _myString;

static MyClass()
{
    MyObject obj = new MyObject();
    obj.someSetupHere();
    _myString = obj.ToString();
}
+5

All Articles