Does C# support the use of static local variables?

No, C# does not support this. You can come close with:

private static System.Text.RegularExpressions.Regex re =
         new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");

private static string AppendCopyToFileName(string f)
{

}

The only difference here is the visibility of 're'. It is exposed to the classm not just to the method.

The re variable will be initialized the first time the containing class is used in some way. So keep this in a specialized small class.


Unfortunately, no. I really loved this possibility in C.

I have an idea what you could do.

Create a class that will provide access to instance-specific values, which will be preserved statically.

Something like this:

class MyStaticInt
{
    // Static storage
    private static Dictionary <string, int> staticData =
        new Dictionary <string, int> ();

    private string InstanceId
    {
        get
        {
            StackTrace st = new StackTrace ();
            StackFrame sf = st.GetFrame (2);
            MethodBase mb = sf.GetMethod ();

            return mb.DeclaringType.ToString () + "." + mb.Name;
        }
    }

    public int StaticValue
    {
        get { return staticData[InstanceId]; }

        set { staticData[InstanceId] = value; }
    }

    public MyStaticInt (int initializationValue)
    {
        if (!staticData.ContainsKey (InstanceId))
            staticData.Add (InstanceId, initializationValue);
    }
}

Can be used this way...

class Program
{
    static void Main (string[] args)
    {
        // Only one static variable is possible per Namespace.Class.Method scope
        MyStaticInt localStaticInt = new MyStaticInt (0);

        // Working with it
        localStaticInt.StaticValue = 5;
        int test = localStaticInt.StaticValue;
    }
}

It's not a perfect solution, but an interesting toy.

You can only have one static variable of this type per Namespace.Class.Method scope. Won't work in property methods - they all resolve to the same name - get_InstanceId.


Why not create a static readonly member on your class and initialize it in a static constructor maybe?

This will give you the same performance benefit - it will only get initialised once.

Tags:

C#

Static