C#'s const vs. readonly

A quick synopsis on the differences between 'const' and 'readonly' in C#:

'const':
  • Can't be static.
  • Value is evaluated at compile time.
  • Initiailized at declaration only.
'readonly':
  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in the constructor.
Published Tuesday, January 27, 2004 10:37 AM by PSteele

Comments

# re: C#'s const vs. readonly

You can't use the static keyword with a const because it would be redundant. You can think of const as a subset of static.

Consts are static, not instance members.

Tuesday, January 27, 2004 10:45 AM by Sherrod

# re: C#'s const vs. readonly

make it more understandable

Saturday, June 5, 2004 6:42 AM by vijaykishan

# re: C#'s const vs. readonly

if you need the value in a switch statement then you must use the const qualifier.

Monday, August 9, 2004 4:19 PM by code_toad

# re: C#'s const vs. readonly

readonly fields can have different values depending on the constructor used.if u declayed const type member and later on want to change the value then you have to compile not only this but all referenced project.

Tuesday, October 10, 2006 3:29 AM by Prem S Pandey

# re: C#'s const vs. readonly

Const = value assigned at Compile time and unchangeable once established.

readonly = value assigned at run time and unchangeable once established.

Wednesday, August 29, 2007 7:26 AM by Narayan Choudhray

# re: C#'s const vs. readonly

The link provided by DG was really useful. Thanks DG.

Tuesday, September 11, 2007 6:37 AM by Prashanth