Static variable in C#
Many developers have trouble understanding the functionality of static variables in C#. This article aims to clarify their uses and usage, while explaining why static variables cannot be declared inside methods.
What are static variables?
Static variables are class-level variables that are shared among all instances of that class. Its value is shared among all objects created from the class.
When do I use static variables?
In the case where multiple instances of a class are required to maintain values, static variables are usually used. Some typical use cases include:
Why can't static variables be declared inside a method?
Static variables are declared outside the method because they have different scopes from instance-level variables. Instance-level variables exist only within the scope of the object instance, while static variables exist in the class itself. Therefore, static variables cannot be declared inside a method because the method has its own isolation scope.
Example:
Consider the following code, which demonstrates the difference between static variables and instance-level variables:
public class Book
{
public static int myInt = 0; // 静态变量
public int instanceInt = 5; // 实例级变量
}
public class Exercise
{
static void Main()
{
Book book1 = new Book();
book1.instanceInt ; // 增加实例级变量
book1.myInt ; // 增加静态变量
Book book2 = new Book();
Console.WriteLine(book2.instanceInt); // 输出 5
Console.WriteLine(book2.myInt); // 输出 1
}
}
In this example:
myInt
is a static variable that is incremented by 1 every time any object of the Book
class is modified. instanceInt
is an instance-level variable that increments by 1 only to the specific Book
object to which it belongs. in conclusion:
Static variables are powerful tools for storing data shared between multiple instances of a class. Understanding their uses and usage is essential for effective C# programming. However, it is important to remember that static variables cannot be declared inside methods due to different scopes of them.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3