C# Static Variables: Purpose and Usage
In C#, static variables occupy a unique position in the programming world. They are shared among all instances of the class, providing a convenient way to store information that is consistent throughout the class.
Why declare static variables?
Static variables have three main uses:
Why can’t static variables be declared inside a method?
Unlike instance variables that are associated with a specific instance of a class, static variables belong to the class itself. Therefore, they must be declared at the class level, outside of any methods.
Example
Consider the following example:
<code class="language-csharp">class Book { public static int myInt = 0; } public class Exercise { static void Main() { Book book = new Book(); Console.WriteLine(book.myInt); // 显示错误 } }</code>
In this code, the error occurs because the static variable myInt cannot be accessed through an instance of the class. To access it, you need to reference it directly:
<code class="language-csharp">Console.WriteLine(Book.myInt);</code>
Practical application of static variables
Let’s delve into a more detailed example illustrating the use of static variables. The following code demonstrates how a static variable stores a running total:
<code class="language-csharp">class Counter { public static int TotalCount { get; set; } public void AddCount(int value) { TotalCount += value; } } public class Program { static void Main() { var counter1 = new Counter(); counter1.AddCount(5); var counter2 = new Counter(); counter2.AddCount(10); Console.WriteLine(Counter.TotalCount); // 输出:15 } }</code>
In this case, the TotalCount variable shared between all Counter instances is used to hold the running total of the added values. Each time a new Counter is created, it inherits the latest value stored in TotalCount.
Conclusion
Static variables in C# provide a powerful mechanism to manage shared information among classes. By understanding their purpose and usage, developers can optimize memory utilization, enforce singleton patterns, and facilitate global access to important data.
The above is the detailed content of How Do Static Variables Function and Why Can't They Be Declared Inside Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!