Home > Uncategorized > Static Readonly Vs Const

Static Readonly Vs Const

Just as a reminder for myself: http://msmvps.com/blogs/rakeshrajan/archive/2005/05/01/45260.aspx

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).

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment