Understanding Static Variables in C#
Static variables in C# are a powerful tool, but their usage is specific. Crucially, a static variable maintains its value across all instances of a class. This contrasts with non-static variables:
<code class="language-csharp">public class Variable { public int i = 5; public void test() { i = i + 5; Console.WriteLine(i); } }</code>
Here, each instance of Variable
has its own independent i
value. However, with a static variable:
<code class="language-csharp">public class Variable { public static int i = 5; public void test() { i = i + 5; Console.WriteLine(i); } }</code>
All instances share the same i
value. Changing i
in one instance affects all others.
The restriction against declaring static variables within methods is intentional. Static variables belong to the class itself, not a specific method call. Their role is to persist across instances and the program's execution. Therefore, declaring them within methods is logically inconsistent and disallowed.
The above is the detailed content of When and Why Are Static Variables Useful in C#?. For more information, please follow other related articles on the PHP Chinese website!