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?
What about this, since you only want it to be initialized if it's used:
It is duplicate from Why doesn't C# support local static variables like C does?
But still, I think you will find my answer useful.
Three years later...
You can approximate it with a captured local variable.
No, C# does not support this. You can come close with:
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:
Can be used this way...
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.
C# doesn't support static local variables. In addition to what has been posted above, here's a link to an MSDN blog entry on the subject:
http://blogs.msdn.com/b/csharpfaq/archive/2004/05/11/why-doesn-t-c-support-static-method-variables.aspx