26

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?

2
  • Actually this is rather the duplicate: stackoverflow.com/questions/755685/c-static-readonly-vs-const I saw it before posting but it goes into depth before it explains it with simple English
    – s5s
    Commented Nov 27, 2011 at 22:34
  • That's a good link, especially the second answer with respect to the compilation differences between const and static readonly.
    – Dunes
    Commented Nov 27, 2011 at 22:35

1 Answer 1

35

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.