Svish Svish - 1 year ago 123
C# Question

Static readonly vs const

I've read around about

static readonly
fields. We have some classes which contains only constant values. Used for various things around in our system. So I am wondering if my observation is correct:

Should these kind of constant values always be
static readonly
for everything that is public? And only use
for internal/protected/private values?

What do you recommend? Should I maybe even not use
static readonly
fields, but rather use properties maybe?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download