Alex Rivera | Logout

Declaring a const double[] in C#?

Asked 2009-07-10T14:18:01.363
45

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?

Edit
Report

2 Answers

3

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:

readonly double[] a = new double[]{1, 2, 3};
...
a = new double[] {2,3}; // this won't compile;
a[1] = 4; // this will compile, run and result the array to {1, 4, 3}

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.

answered 2010-04-22T20:33:10.847
2

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#.

answered 2009-07-10T14:26:26.780

Your Answer