const vs readoly vs static
Constant and ReadOnly (const and readonly) variables in C# make a variable whose value cannot be changed. The static keyword is used to create a static variable that shares a value for all instances of that class. In this article we will learn about the differences between them.
Constant
Constant fields or constant variables must be assigned a value at the time of declaration, then their value cannot be changed. By default, constant is static, so you cannot declare the static keyword for the constant variable.
A constant variable is a compile-time constant. A constant variable can be initialized by an expression but must ensure that the operands in the expression must also be constants.
You can apply the const keyword to primitive types (byte, short, int, long, char, float, double, decimal, bool), enum, a string, or a reference type that can be assigned a value. null.
Constant variables can be assigned all access modifiers such as public, private, protected, internal. You use constant variables in cases where you are sure their value will not change.
ReadOnly
A Readonly variable can be initialized at declaration time or in the class's constructor. So readonly variables can be used as run-time constants.
Readonly can be applied to both value and reference types except delegates and events. Use readonly when you want to create constant variables at runtime.
Static
The static keyword is used to make a variable or member static, meaning its value will be shared by all objects and not attached to any particular object. The static keyword can be applied to classes, fields, properties, operators, events, and constructors, but cannot be used for indexes, destructors, or anything other than classes.
Knowledge of static keyword
If the static keyword is applied to a class, all elements in the class must also be static
Static methods can only access other static elements in the class. Static properties are used to set and get values ​​for the values ​​of static variables in the class.
Static constructors cannot have parameters. Access modifiers cannot be applied to static constructors, there is always a public default constructor to initialize static variables for clas
Last updated