Prefer readonly to const
Effective C# (Covers C# 4.0): 50 Specific Ways to Improve Your C# by Bill Wagner.
C# has two different versions of constants:
1 2 3 4 5 |
// Runtime constant: public static readonly int ThisYear = 2017; // Compile time constant: public const int Millennium = 2000; |
runtime constant: readonly
– slightly slower, but far flexible.
– cannot be declared with method scope.
– can be any type.
– resolved at runtime.
– The IL is generated when you reference a readonly constant references the readonly variable, not the value.
– So you can distribute an infrastructure assembly includes runtime constant without rebuilding the application assembly.
compile-time constant: const
– slightly faster, but far less flexible.
– can be declared inside methods.
– can be used only for primitive types (built-in integral and floating-point types), enums, or strings.
– cannot be initialized using the new operator, even when the type being initialized is a value type.
– Use when performance is critical.
– Use when the value will never change between releases.
1 2 |
if (myDateTime.Year == Millennium) // The same IL will be generated as you write the following. if (myDateTime.Year == 2000) |
From Effective C# (Covers C# 4.0): 50 Specific Ways to Improve Your C# by Bill Wagner.