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
Not in C#, only in Visual Basic .NET:
Sub DoSomething()
Static obj As Object
If obj Is Nothing Then obj = New Object
Console.WriteLine(obj.ToString())
End Sub
VB.NET have lot of nice things that C# does not have, thats why I choose VB.NET.
Sure. You just have to declare the private static variable outside of the method.
private static readonly System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex( "\\(copy (\\d+)\\)$" );
private static string AppendCopyToFileName( string f )
{
//do stuff.
}
This is effectively what you are doing with the only difference being that "re" has visibility to the entire class as opposed to just the method.
What about this, since you only want it to be initialized if it's used:
private static System.Text.RegularExpressions.Regex myReg = null;
public static void myMethod()
{
if (myReg == null)
myReg = new Regex("\\(copy (\\d+)\\)$");
}
Three years later...
You can approximate it with a captured local variable.
class MyNose
{
private static void Main()
{
var myNose= new MyNose();
var nosePicker = myNose.CreatePicker();
var x = nosePicker();
var y = nosePicker();
var z = nosePicker();
}
public Func<int> CreatePicker()
{
int boog = 0;
return () => boog++;
}
}
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.
Nesting the related members in an inner class as you have shown in question is the cleanest most probably. You need not push your parent method into inner class if the static variable can somehow get the caller info.
public class MyClass
{
...
class Helper
{
static Regex re = new Regex("\\(copy (\\d+)\\)$");
string caller;
internal Helper([CallerMemberName] string caller = null)
{
this.caller = caller;
}
internal Regex Re
{
//can avoid hard coding
get
{
return caller == "AppendCopyToFileName" ? re : null;
}
set
{
if (caller == "AppendCopyToFileName")
re = value;
}
}
}
private static string AppendCopyToFileName(string f)
{
var re = new Helper().Re; //get
new Helper().Re = ...; //set
}
private static void Foo()
{
var re = new Helper().Re; //gets null
new Helper().Re = ...; //set makes no difference
}
}
You can avoid hard coding of method names in the property using some expression tree tricks.
You can avoid the helper constructor and make the property static, but you need to get the caller info inside the property, via using StackTrace
.
Lastly, there is always const
possible inside a method, but then one, it's not variable, two, only compile time constants are allowed. Just stating.