Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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++;
}
question from:https://stackoverflow.com/questions/4525654/c-static-variable-in-a-static-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
881 views
Welcome To Ask or Share your Answers For Others

1 Answer

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++;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...