'Static readonly' vs. 'const'
Solution 1:
public static readonly
fields are a little unusual; public static
properties (with only a get
) would be more common (perhaps backed by a private static readonly
field).
const
values are burned directly into the call-site; this is double edged:
- it is useless if the value is fetched at runtime, perhaps from config
- if you change the value of a const, you need to rebuild all the clients
- but it can be faster, as it avoids a method call...
- ...which might sometimes have been inlined by the JIT anyway
If the value will never change, then const is fine - Zero
etc make reasonable consts ;p Other than that, static
properties are more common.
Solution 2:
I would use static readonly
if the Consumer is in a different assembly. Having the const
and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
Solution 3:
A few more relevant things to be noted:
const int a
- must be initialized.
- initialization must be at compile time.
readonly int a
- can use a default value, without initializing.
- initialization can be done at run time (Edit: within constructor only).