tags:

views:

538

answers:

5

Should I prefer the use of readonly (run time constants) or const (compile time constants)? What are the pluses and minuses of each or in what cases is one better than the other?

A: 

In practice it will make little difference, but compile-time constants are obviously not going to be slower than readonly. However relatively few types can be made compile-time constant, whereas anything can be readonly.

The performance difference between readonly and non-readonly fields is negligible, so use it as the design dictates rather than for for any performance benefit. I often use readonly for fields which are injected in the constructor and should not be modified thereafter, just to make sure I don't do something stupid with them later.

Matt Howells
+1  A: 

const is generally more performant, but can only be used for value types. At compile time the references to the const value are replaced with the actual value. This is faster than dereferencing the value, but makes it hard to patch individual assemblies in place with predictable behaviour.

(static) readonly is slightly slower than const but offers more flexibility, such as being able to be used for any type, and the behaviour is more likely to match your intention if used publicly and accessed by another assembly (i.e. if you change static readonly values in an assembly then the other assemblies that reference the value will pick up the change without having to be recompiled).

Chris
A: 

readonly can be used at the instance level to define members that can only be set at the time the class is instantiated. 'static readonly' therefore does the same thing but at the class level. You should use 'const' if you're defining values at compile time. Use 'readonly' or 'static readonly' when it's possible the values are different at runtime.

Joseph Daigle
+1  A: 

The main diffrence is that const is similar to C #define its value evaluated during compilation while readonly variable remains even after compilation but its value cannot be updated. I personally perfer const unless it's not passible to use it (when declairing const classes) because that what I need is a pre compile define.

Dror Helper