const vs static readonly Fields
-
Hello, I was just wondering if anyone has a good explanation for the differences between static readonly fields and const fields? The differences I can come up with are: 1. const fields can only be initialized at declaration 2. static readonly can be initialized at declaration or in a static constructor (either directly in the static constructor or through another method called from the static constructor using
ref
orout
) 3. static readonly are changeable at runtime (app start); meaning each time the app is run this field can change Example:public class myClass { static readonly DateTime m_MyStart = DateTime.Now; // this will always be different... }
4. const fields are hard coded into the MSIL at compile time; meaning an app might use a constant from an assembly and later that assembly might change the constants, but the app doesn't realize the update until the app itself is rebuilt. (Can anyone rephrase this better than that? I suck at trying to describe this...) Anyone else have differences or corrections to these? Thanks, Nathan --------------------------- Hmmm... what's a signature? -
Hello, I was just wondering if anyone has a good explanation for the differences between static readonly fields and const fields? The differences I can come up with are: 1. const fields can only be initialized at declaration 2. static readonly can be initialized at declaration or in a static constructor (either directly in the static constructor or through another method called from the static constructor using
ref
orout
) 3. static readonly are changeable at runtime (app start); meaning each time the app is run this field can change Example:public class myClass { static readonly DateTime m_MyStart = DateTime.Now; // this will always be different... }
4. const fields are hard coded into the MSIL at compile time; meaning an app might use a constant from an assembly and later that assembly might change the constants, but the app doesn't realize the update until the app itself is rebuilt. (Can anyone rephrase this better than that? I suck at trying to describe this...) Anyone else have differences or corrections to these? Thanks, Nathan --------------------------- Hmmm... what's a signature?That's pretty much it. Const fields can only be used for types where there is a literal representation of the type, and the values are "burned into" the code that uses them. Readonly fields can be used for any type, and the code that uses them references the constructed value at runtime.