Rakesh Rajan's blog

Thoughts on .NET, software and a few trivial things...

Static readonly versus constants

Though both would appear similar – they are both read only and generate almost similar IL code – they have a number of differences.  Here they are:

Constants are evaluated at compile time, whereas static (or static readonly) variables at runtime.

So, when the compiler generates the IL, the value of the constant is burned into the IL wherever it is referenced.  Consequently, when you change the value of a constant, all the client applications referring the constant will have to be recompiled. 

However, if you change the value of a static field, you only need to recompile that library and none of the clients.  This is because the IL generated would only be referencing the static field, and will not have the value burned into it.

Though constants and readonly variables are both read only, readonly is a runtime constant, and can hold references types (like DataSet etc.).  Constants on the other hand cannot hold reference types except for string and null.

Yet another difference is that constants need to be initialized at the declaration itself, whereas readonly fields may be initialized either at the declaration or in a constructor (or in static constructors/type initializers).

Posted: May 01 2005, 11:03 AM by rakeshrajan | with 6 comment(s)
Filed under:

Comments

TrackBack said:

Static readonly versus constantsooeess
# May 24, 2005 1:53 AM

rakeshrajan said:

>>Consequently, when you change the value of a constant, all the client applications referring the constant will have to be recompiled.

that's very interesting... recompiled, like using "csc" (or from inside visual studio)?
# July 21, 2005 10:11 PM

rakeshrajan said:

Any sort of compilation...

- Rakesh Rajan
# July 21, 2005 10:44 PM

TrackBack said:

Static readonly versus constantsooeess
# July 22, 2005 3:24 PM

TrackBack said:

Static readonly versus constantsooeess
# August 3, 2005 8:38 PM

rakeshrajan said:

Good one , clearly differentiates those two.
# September 19, 2005 1:09 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)