I've read around about const
and static readonly
fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:
Should these kind of constant values always be static readonly
for everything that is public? And only use const
for internal
/protected
/private
values?
What do you recommend? Should I maybe even not use static readonly
fields, but rather use properties maybe?
Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor. Constant variables cannot be modified after declaration. Static members can be accessed using ClassName.
const is a constant value, and cannot be changed. It is compiled into the assembly. static means that it is a value not related to an instance, and it can be changed at run-time (since it isn't readonly ). So if the values are never changed, use consts.
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further.
Read-only variables can't access without a class instance. Static readonly: We can define static readonly variable values while declaring as well as only through a static constructor, but not with any other constructor. We can also access these variables without creating a class instance (as static variables).
public static readonly
fields are a little unusual; public static
properties (with only a get
) would be more common (perhaps backed by a private static readonly
field).
const
values are burned directly into the call-site; this is double edged:
If the value will never change, then const is fine - Zero
etc make reasonable consts ;p Other than that, static
properties are more common.
I would use static readonly
if the Consumer is in a different assembly. Having the const
and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With