Declaring a const double[] in C#?

David Božjak picture David Božjak · Jul 10, 2009 · Viewed 39.1k times · Source

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?

Answer

Dykam picture Dykam · Jul 10, 2009

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 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:

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.