Prefer readonly to const

51zy3ojm4kl-_sx379_bo1204203200_

Effective C# (Covers C# 4.0): 50 Specific Ways to Improve Your C# by Bill Wagner.

C# has two different versions of constants:

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.

From Effective C# (Covers C# 4.0): 50 Specific Ways to Improve Your C# by Bill Wagner.

ページトップへ