This question already has an answer here:
I have several constants that I use, and my plan was to put them in a const array of doubles, however the compiler won't let me.
I have tried declaring it this way:
const double[] arr = {1, 2, 3, 4, 5, 6, 73, 8, 9 };
Then I settled on declaring it as static readonly:
static readonly double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
However the question remains. Why won't compiler let me declare an array of const values? Or will it, and I just don't know how?
The problem is that you're declaring a constant array of double, not an array of constant doubles. I don't think there is a way to have an array of constants due to the way arrays work in C#.
This is probably because
is in fact the same as saying
A value assigned to a const has to be... const. Every reference type is not constant, and a array is an reference type.
The solution my research showed was using an static readonly. Or, in your case with a fixed number of doubles, give everything a individual identifier.
Edit(2): A little sidenode, every type can be used const, but the value assigned to it must be const. For reference types, the only thing you can assign is null:
But this is completely useless. Strings are the exception, these are also the only reference type which can be used for attribute arguments.
The compiler error tells you exactly why you can't do it:
From MSDN (http://msdn.microsoft.com/en-us/library/ms228606.aspx)
There is no way to have a const array in C#. You need to use indexers, properties, etc to ensure the contents of the array are not modified. You may need to re-evaluate the public side of your class.
Just to point out though... Static readonly -IS NOT CONST-
This is perfectly valid and not what you were wanting:
You will need to find other ways to protect your array.
I don't know why you needed to make it either constant or readonly. If you really want to make the whole array immutable, then a simple constant/readonly keyword will not help you, and what's worse is, it might also divert you to the wrong way.
For any non-immutable reference types, make them readonly only means you can never re-assign the variable itself, but the content is still changeable. See below example:
Depending on your context, there might be some solutions, one of them is, if what you really need is a list of double, List a = new List() {1,2,3,4,5}.AsReadOnly(); will give you a content-readonly list of double.