4

Possible Duplicate:
What is the difference between const and readonly?

are these interchangeable? can you show me code on how you would apply the two?

Community
  • 1
  • 1
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

3 Answers3

3

No, they aren't.

A const field is literal value embedded in the assembly.
Only primitive values (strings and numbers) can be const, and they are evaluated at compile time.
When you reference a const field, the compiler embeds the literal value of the field. Therefore, if use use a const from another assembly, and the other assembly is recompiled with a different value, your assembly will only use the new value if you recompile it against the new version.


A readonly field is a normal field that cannot be changed outside the constructor.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • answer this one: http://stackoverflow.com/questions/2624796/initialize-byte-array-from-a-portion-of-existing-byte-array-c – Alex Gordon Jun 20 '10 at 20:23
3

Const can't perform evaluations whereas readonly can on initialization. (ie you could read in a value for a readonly variable from a config file or based on some other parameter that is known at runtime, const can only be set to something known at compile time)

heisenberg
  • 9,665
  • 1
  • 30
  • 38
1

A member of any type can be readonly. It simply means the member cannot be reassigned after the construction of the containing class; i.e., it cannot be set to a new object with the = operator. Mutable classes such as collections can still be modified with respect to their members; it's just that, if you have a readonly member that is a collection, it cannot be assigned to an entirely new collection after construction.

A const is not so different from a literal (like 5): it represents an unchanging value and thus only really makes sense in the context of specifying a value (as opposed to an object).

Dan Tao
  • 125,917
  • 54
  • 300
  • 447