Search code examples
c#static

Does C# support the use of static local variables?


Related: How do I create a static local variable in Java?


Pardon if this is a duplicate; I was pretty sure this would have been asked previously, and I looked but didn't find a dupe.

Is it possible for me to create a static local variable in C#? If so, how?

I have a static private method that is used rarely. the static method uses a Regular Expression, which I would like to initialize once, and only when necessary.

In C, I could do this with a local static variable. Can I do this in C#?

When I try to compile this code:

    private static string AppendCopyToFileName(string f)
    {
        static System.Text.RegularExpressions.Regex re =
            new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
    }

...it gives me an error:

error CS0106: The modifier 'static' is not valid for this item


If there's no local static variable, I suppose I could approximate what I want by creating a tiny new private static class, and inserting both the method and the variable (field) into the class. Like this:

public class MyClass 
{
    ...
    private static class Helper
    {
        private static readonly System.Text.RegularExpressions.Regex re =
            new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");

        internal static string AppendCopyToFileName(string f)
        {
            // use re here...
        }
    }

    // example of using the helper
    private static void Foo() 
    {
       if (File.Exists(name)) 
       {
           // helper gets JIT'd first time through this code
           string newName = Helper.AppendCopyToFileName(name);
       }
    }
    ...
}

Thinking about this more, using a helper class like this there would yield a bigger net savings in efficiency, because the Helper class would not be JIT'd or loaded unless necessary. Right?


Solution

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