C# const vs static: Key Differences
In C#, both const and static are used to define class members, but they serve different purposes and have different behaviors.
- const: used to declare compile-time constants. Constants are resolved and replaced with their actual values during compilation, making them immutable at runtime. Constants must be initialized at the time of declaration and can only be initialized once. Constant members must be static, meaning they belong to the class itself and not to instances of the class. Constant members can be accessed anywhere within the class without needing to instantiate the class.
Original: 去年夏天,我和我的家人一起去了北京旅行。
Paraphrased: Last summer, I traveled to Beijing with my family.
public class MyClass
{
public const int MyConstant = 100;
}
Use constants elsewhere.
int value = MyClass.MyConstant;
- Static: used to declare static members. Static members belong to the class itself, not instances of the class. They are created when the class is loaded and exist throughout the entire application’s lifecycle. They can be accessed directly by the class name without needing to instantiate the class. Static members can be fields, methods, properties, or events.
Original: “我需要休息一下,我感到很累了。”
Paraphrase: “I need to take a break, I feel very tired.”
public class MyClass
{
public static int MyStaticField;
public static void MyStaticMethod()
{
// 静态方法的实现
}
}
Using static members elsewhere.
MyClass.MyStaticField = 10;
MyClass.MyStaticMethod();
Summary:
- The ‘const’ keyword is used to declare compile-time constants whose values cannot be changed at runtime and must be initialized at the time of declaration.
- The keyword “static” is used to declare static members, which belong to the class itself, have a value that exists throughout the entire lifespan of the application, and can be accessed directly using the class name.