Sunday, 25 March 2012

Static readonly vs const

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)

http://blogs.msdn.com/b/csharpfaq/archive/2004/12/03/274791.aspx

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.

http://stackoverflow.com/questions/755685/c-static-readonly-vs-const

No comments:

Post a Comment