Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a const double[] in C#? [duplicate]

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?

like image 332
David Božjak Avatar asked Jul 10 '09 14:07

David Božjak


People also ask

What is const double in C?

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; )

How do you declare constants in C?

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.

How do you declare a two way constant?

In C/C++ program we can define constants in two ways as shown below: Using #define preprocessor directive. Using a const keyword.

How do you declare a constant?

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.


1 Answers

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.

like image 161
Dykam Avatar answered Sep 20 '22 13:09

Dykam