Can you have a static variable in a static method? Would the value of this variable be preserved across all calls to the method?
eg.
public static void MyMethod()
{
static int x = 0;
x++;
}
Can you have a static variable in a static method? Would the value of this variable be preserved across all calls to the method?
eg.
public static void MyMethod()
{
static int x = 0;
x++;
}
No.
You can't have local static variables.
From MSDN:
C# does not support static local variables (variables that are declared in method scope).
And here:
The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
As you can see, local variables are not mentioned.
You can, however use a static field:
public class MyClass
{
private static int MyVariable = 10;
public static void MyMethod()
{
MyVariable++;
}
}
MyVariable
is only used in MyMethod
it belongs in MyMethod
, not exposed to the rest of the class. –
Condonation strtok
function even possible. From the POSIX strtok page: This function uses static storage to keep track of the current string position between calls. I wrote a variant of it in C++ that ignored empty records and accepted any delimiter that could be represented by a C++ String class. Knowing how these things work should make it replicate-able in any language, but alas, this is one weakness of C#. –
Incomprehensive No, but you could have:
private static int x = 0;
public static void MyMethod()
{
x++;
}
[ThreadStatic]private static int x = 0;
if you do that? –
Precinct Here is sort of a hackish way to accomplish what you're trying to do. Turn MyMethod
into an Action
that creates a closure on x
. The variable x
will only be visible to the innermost delegate, and behaves like a static variable. If anyone has any suggestions for improving this pattern let me know.
public static readonly Action MyMethod = new Func<Action>(delegate ()
{
var x = 0;
return delegate () { x++; };
}).Invoke();
//example usage:
public void Init() {
MyMethod();
}
© 2022 - 2025 — McMap. All rights reserved.
Shared
local variable before in VB.NET? This isn't natively supported by the CLR in any case, and VB.NET has to use some behind-the-scenes trickery to create this effect. – Daub