They say the difference between readonly and const is that const is compile-time (while readonly is run time). But what exactly does that mean, The fact that it's compile time? Everything gets compiled to byte code doesn't it?
4.1. Compile-Time Constants. A Java variable is a compile-time constant if it's of a primitive type or String, declared final, initialized within its declaration, and with a constant expression. Strings are a special case on top of the primitive types because they are immutable and live in a String pool.
A variable that is declared using the const keyword cannot be assigned any other value. Also, the variable is known as a compile-time constant, which in turn means that its value must be declared while compiling the program.
Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.
Compile-time and Runtime are the two programming terms used in the software development. Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running.
It means that const variables get written to the location they are referenced from. So, say you have an 2 libraries, one with a const
variable:
// Library A
const int TEST = 1;
// Library B
void m ()
{
Console.WriteLine(A.TEST);
}
The variable is actually written, at compile time, into B. The difference is, if you recompile A but not B, B will have the "old" value. This won't happen with readonly
variables.
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