On Sep 29, 11:46Â am, "Peter Morris" <mrpmorri...@SP AMgmail.comwrot e:
>const is set at compile time, readonly is set within the constructor.
>
>
Any reason to use readonly then?
Two reasons:
-- when you don't know the value of the variable at compile-time
-- when the variable is a type that doesn't support "const" (i.e. most
reference types)
Yes. When you have a class that accepts a value in its constructor, you
store the passed value but do not think it should change. Marking it
readonly makes sure you don't screw up later and try to change it.
1) You cannot initialize a compile-time constant using the new operator
2) Const must be used when the value types are avaiable at compile time
3) For reference type constants use 'readonly'
"Peter Morris" <mrpmorrisNO@SP AMgmail.comwrot e in message
news:egCnM4mIJH A.4996@TK2MSFTN GP03.phx.gbl...
>Any reason to use readonly then?
>
Yes. When you have a class that accepts a value in its constructor, you
store the passed value but do not think it should change. Marking it
readonly makes sure you don't screw up later and try to change it.
>
Few more info
>
1) You cannot initialize a compile-time constant using the new operator
2) Const must be used when the value types are avaiable at compile time
3) For reference type constants use 'readonly'
Strings are reference types, and they can be const - and in fact any
other reference type field can be const to, but the only supported
value is null :)
const is set at compile time, readonly is set within the constructor.
>
Any reason to use readonly then?
Versioning. When you make a library, you should only use non-private/
internal const if you can guarantee that the value won't change in the
future versions of the library. The reason is simple: when an
application references your library, and its code uses the constant,
the value of that constant is substituted directly into the compiled
assembly. Even if you later change the library to a newer one, the
compiled client code will still use the old value of the constant.
With readonly, it is not the case - it is a proper variable, and its
value is actually read at run-time when the assembly is loaded, so if
it changes in the assembly, the change will be seen by all clients on
the next run.
In general, when in doubt, prefer readonly. The only thing you really
lose is the ability to use it as a case label in a switch statement;
but you will certainly not introduce silent breakage, as is possible
with const and separate builds.
Comment