I am eager to know the difference between a const variable and a static variable.
As far as I know a const is also static and can not be accessed on instance variable that's same like static , then what is the difference between them ?
Please explain ...
Static is a storage specifier. Const/Constant is a type qualifier. Static can be assigned for reference types and set at run time. Constants are set at compile-time itself and assigned for value types only.
They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.
Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.
The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.
const
fields can only hold value types or System.String
. They must be immutable and resolvable at compile-time.
static readonly
fields can and generally do hold reference types, which (other than strings) can only be created at runtime. These can (but shouldn't) be mutable types; the only thing that cannot change is the reference itself.
If you need to maintain a "constant" set of instances that are reference types, you generally do it with a set of public static readonly
fields, such as the members of System.Drawing.SystemColors.
Last but not least, initialization of a readonly
field can be deferred until the execution of a constructor, which means that it even though it can only be written to once, it does not always have to be initialized with the exact same value. True constants declared with const
can only ever have a single value (specified at compile time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With