Answered Questions

  • What is the difference between const and static read-only?

    The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it:-- in the variable declaration (through a variable initializer).-- in the static constructor (instance constructors if it's not static).

    Star Read Best Answer

    Editorial / Best Answer

    Answered by: Eddie Quiroz

    • Sep 3rd, 2005


    A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. Declaring fields as const protects both you and other programmers from accidentally changing the value of the field. Also note that with const fields, the compiler performs some optimization by not declaring any stack space for the field. The readonly keyword is similar to const, with two exceptions. First, the storage of a readonly field is the same as a regular read-write field, and thus there is no performance benefit. Secondly, readonly fields can be initialized in the constructor of the containing class.

    chandra_123

    • Apr 7th, 2009

    As static read-only variables must be initialized in the static constructor (static constructor cannot have parameters and it cannot be called manually), it is efficient to used const variables over static read-only variables if you know the values at creation of these variables.