✅ readonly keyword vs const keyword and use-case
Hello guys, I just read a bit about the readonly keywords. From what I've read, using the
readonly
keyword, we can only assign a particular value to a variable either at declaration level or when using the constructor. In constrast with the const
keyword, I think we can only assign a value to it in the declaration part.
I read that using const means the value is determined at compile-time itself while using readonly means value is determined at run-time.
My first question concerning the readonly
keyword:
When we declare a property, consider the following:
My question is, if we omit the readonly keyword and just use { get; } without the set keyword, does the property behave as readonly?
Second question is, what are the use cases of readonly vs const keyword please20 Replies
Yes
caps
readonly
is not valid for propertiesyeah just read that
we use
readonly
for fields while {get ; } for properties which are "read-only" ?{ get; } is readonly
basically
yep I see
what about the use cases of
readonly fields
vs const fields
pleasereadonly is runtime and not static
const is compile time and static
you have to use static readonly to make it static
const
behaves like static readonly
, but as said, its a compile time constant
if a value never changes and is known at compile time, use const
if you can
you can't have const
arrays etc, so there are cases where static readonly
is needed
non-static readonly is almost only used for stuff passed in via the constructorwell, unless it's a
null
array x3ero
REPL Result: Success
Compile: 194.036ms | Execution: 16.977ms | React with ❌ to remove this embed.
I have never needed one of those :p
yep I see
Noted
(but this is useless and you shouldn't really use it...)
So to summarise:
If we know a value is going to be constant at compile itme, use
const
else use readonly
. The difference is that const
is for the entire class itself (static readonly) while readonly
can differs for each instances. Now, const
can only be use for value type (well I guess there are exceptions like the null array) so if we want to make a reference type "constant"; we need to use readonly
keyword in this case?yeah, and the value of the reference type can still be mutated
readonly only applies to the variable itself, not the thing it contains
yep I see
for example you could make collections
readonly
a lot of the time
each instance of C
would have a new _someList
but the list will never need to be re-assignedyep, but we can add items to it though
you can just call
.Clear()
to empty the values of the list
or add and remove, exactlyyep 💯
It clearer now, thanks guys, really appreciate