tags:

views:

3814

answers:

5

I've read around about const and 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 const for internal/protected/private values?

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

+37  A: 

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.

Marc Gravell
Thanks Marc. Like alot of coders, I think I've just been randomly using which ever depending on my mood.
Dead account
Why a property over a field? If it's an immutable class, I see no difference.
Michael Hedgpeth
@Michael - same reasons as always; it hides the implementation. You may find (later) that you need to be lazy loaded, configuration based, a facade, or whatever. In reality, either would often be fine...
Marc Gravell
+10  A: 

One thing to note is const is restricted to primitive/value types (the exception being strings)

Chris S
+5  A: 

Some other things

const int a

  • must be initialized
  • initialization must be at compile time

readonly int a

  • can use default value, without initializing
  • initialization can be at run time

but please see : http://en.csharp-online.net/const,_static_and_readonly

Peter
+2  A: 

My preference is to use const whenever I can, which as mentioned above is limited to literal expressions or something that does not require evaluation.

If I hot up against that limitation, then I fallback to static readonly, with one caveat. I would generally use a public static property with a getter and a backing private static readonly field as Marc mentions here.

Peter Meyer
+4  A: 

I would use static readonly if the Consumer is in a different assembly. Having the const and the consumer in two differen assemblies is a nice way to shoot yourself in the foot.

Michael Stum