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?

6

3 Answers 3

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.

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.