Constants & Readonly
Because a constant value never changes,
constants are always considered to be part of the defining type. In other
words, constants are always considered to be static members, not instance
members. Defining a constant causes the creation of metadata. When code refers
to a constant symbol, compilers look up the symbol in the metadata of the assembly
that defines the constant, extract the constant’s value, and embed the value in
the emitted Intermediate Language (IL) code Because a constant’s value is
embedded directly in code, constants don’t require any memory to be allocated
for them at runtime. In addition, you can’t get the address of a constant and
you can’t pass a constant by reference. These
constraints also
mean that constants don’t have a good cross-assembly versioning story, so you
should use them only when you know that the value of a symbol will never change
Const instance fields
·
Constants are static by
default
·
They must have a value
at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
·
Could be declared within
functions
·
Are copied into every
assembly that uses them (every assembly gets a local copy of values)
·
Can be used in
attributes
·
The value of your const
property is set at compile time and can't change at runtime
·
A const field can only be initialized at the
declaration of the field
Readonly instance fields
·
Are evaluated when
instance is created
·
A readonly field
can be initialized either at the declaration or in a constructor
Therefore, readonly fields can have different values depending on the
constructor used
Const
|
Readonly
|
The value of your const property is set at
compile time and can't change at runtime
|
The value of your const property is set at run
time.
|
They
Can not be static
|
They Can be static
|
Value
of const in given in the declaration time only.
As
given in below example if you assignee the value to const variable you will
get the compile time error.
|
Value
of const in given in the declaration time as well as in the constructor.
You
can assign the value to the read only variable in the constrctor.
|
|
|
|
|
When to use what
·
Use const when you have a variable of a type you can know
at runtime (string literal, int, double, enums,...) that you want all instances
or consumers of a class to have access to where the value should not change.
·
Use static when you have data that you want all instances
or consumers of a class to have access to where the value can change.
·
Use static readonly when you have a variable of a type that you
cannot know at runtime (objects) that you want all instances or consumers of a
class to have access to where the value should not change.
·
Use readonly when you have an instance level variable you
will know at the time of object creation that should not change.
No comments:
Post a Comment