Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const vs. static readonly [duplicate]

Tags:

Possible Duplicate:
What is the difference between const and readonly?

So from what I read, in C#, const and static readonly will both make a value unalterable during the execution of a program.

However, const should be used with quantities which are unlikely to ever change (e.g. pi, radius of earth, litters per gallon etc.).

On the other hand, static readonly should be used with values that currently are constant but might/will change in the future (e.g. software version, a multiplier in an algorithm etc.).

Have I got it right?

like image 864
s5s Avatar asked Nov 27 '11 22:11

s5s


People also ask

What is difference between constant and read-only?

readonly is a constant defined at runtime. const is used to create a constant at compile time. readonly field value can be changed after declaration. const field value cannot be changed after declaration.

What is the difference between static const and readonly?

The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.

Why would you use readonly vs const in C #?

A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a 'const' is always constant but 'readonly' is read-only once it is assigned.

Should I use const or static?

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.


1 Answers

I don't know about your second item (I would probably use a constant for a software version or an algorithm… constant) but there is one key difference between the two: const can only hold basic types such as string, bool, or numeric types. static readonly can hold any object. So, for example, I often use static readonly to store resources like Bitmap objects. Those cannot be const.

like image 116
Ry- Avatar answered Oct 20 '22 19:10

Ry-