Const
is baked into the client code. Readonly
isn't. But const
is faster. May be only slightly though.
The question is, is there ever any scenario where you should prefer const
over readonly
? Or to rephrase, are we not practically always better off using a readonly
instead of a const
(keeping in mind the above-said baking thing)?
The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
Summary. As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
The const keyword is typically used in C# language when there is an intention to have an immutable value across the system. Once a const field is initialized with a specific value, it can't be changed after that.
I believe the only time "const" is appropriate is when there is a spec that you're coding against that is more durable than the program you're writing. For instance, if you're implementing the HTTP protocol, having a const member for "GET" is appropriate because that will never change, and clients can certainly hard-code that into their compiled apps without worrying that you'll need to change the value later.
If there's any chance at all you need to change the value in future versions, don't use const.
Oh! And never assume const is faster than a readonly field unless you've measured it. There are JIT optimizations that may make it so it's actually exactly the same.
Const vs readonly:
A quick synopsis on the differences between 'const' and 'readonly' in C#: 'const':
- Can't be static.
- Value is evaluated at compile time.
- Initiailized at declaration only.
'readonly':
- Can be either instance-level or static.
- Value is evaluated at run time.
- Can be initialized in declaration or by code in the constructor.
Correction: the above states const can't be static. That is a misnomer. They can't have the static keyword applied because they are already static.
So you use const for static items that you want evaluated 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