Stupid Question 46: Static readonly VS Const, which one to use?
The weather in Gothenburg is pretty constant… rain, rain and more rain
If I have a value that will never change I’ve always used const (and if it is a value type), and I’ve used static readonly with complex types, although not to often. But, I will gladly admit that today I googled this to double check whether I’ve been thinking right or not- as I couldn’t really remember where I first got my habits from :D
A static readonly field is useful when a symbolic name for a constant value is desired, but when the type of the value is not permitted in a const declaration, or when the value cannot be computed at compile-time
public static readonly Color Black = new Color(0, 0, 0);
public const int c1 = 5.0;
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks;
Last modified on 2012-09-17