Readonly vs. Const

29 06 2011

C# has two different versions of constant: compile-time (const) and runtime (readonly) constants. Compile-time constants are slightly faster but significantly less flexible than runtime constants.

Compile-time and runtime constants are accessed differently. Compile-time constants are replaced with the value of that constant in your object code. Runtime constants are evaluated at runtime, the IL generated references the readonly variable, not the value. Compile-time constants are limited to numbers and strings because these are the only types that can be replaced with literal values in the IL. Runtime constants can be any type, you must initialize them in a constructor or an initializer.

public const int BirthYear = 1982;

int myYear = BirthYear;
//compiles to the same IL as
int myYear = 1982;

The way in which the different constants are evaluated affects runtime compatibility across assemblies. When you reference a const in another assembly and that const changes BOTH assemblies must be recompiled to pick up the change (because the literal value is placed in the assembly IL). A change to a readonly value in another assembly does not require the referencing assembly to be recompiled, it still references to the correct value because it gets resolved at runtime.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: