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?
This can be used in several ways. Examples: Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )
The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
In C/C++ program we can define constants in two ways as shown below: Using #define preprocessor directive. Using a const keyword.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.
This is probably because
static const double[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
is in fact the same as saying
static const double[] arr = new double[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9};
A value assigned to a const has to be... const. Every reference type is not constant, and an array is a reference type.
The solution, my research showed, was using a static readonly. Or, in your case, with a fixed number of doubles, give everything an 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:
static const double[] arr = null;
But this is completely useless. Strings are the exception, these are also the only reference type which can be used for attribute arguments.
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