Tuesday, March 17, 2009

 

"const" vs "static readonly"

A class can have some fields marked with the keyword const and others marked with the keywords static readonly. These are conceptually very similar, yet subtly different. Your choice about which to use must be based on these subtle differences.































property const static readonly
evaluation time The value of a const field is determined at compile-time. The value of a static readonly field is determined at run-time.
types The type for a const field must be a sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum type, or a reference type. The type for static readonly field can be anything, including a struct or an instance of an object allocated via the new operator.
reference types Although a const can technically be a reference type, the only reference type it can be is a string or null since the new operator cannot be used to create an instance of an object at compile-time. Because a static readonly field is determined at run-time, it can hold a reference to an object allocated via the new operator. However, since it is both static and readonly, it must be assigned in the declaration and/or static constructor.
switch statements A const field can be used as a case in a switch statement because the compiler is able to determine the value to enter in the jump table.
A static readonly field cannot be used as a case in a switch statement since the value was not known at compile time.
Other Assemblies At compile-time, the compiler obtains the value of a const and inserts it directly into the compiled output of the code that references the constant. This can have undesirable results! Assume, for example, that const is defined in assembly A1 and is used in assembly A2. If assembly A1 is recompiled and redistributed without also recompiling and redistributing assembly A2, then A2 will continue to use the old value of the constant that was in affect at the time assembly A2 was last compiled. Since a static readonly field is assigned and obtained at run-time, other assemblies that reference that field will always use the most recent value of that field instead of obtaining the value at the time the assembly was compiled.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]