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

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.


From MSDN (http://msdn.microsoft.com/en-us/library/ms228606.aspx)

A constant-expression is an expression that can be fully evaluated at compile-time. Because the only way to create a non-null value of a reference-type [an array] is to apply the new operator, and because the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.


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:

class TestClass
{
    public static readonly string[] q = { "q", "w", "e" };
}

class Program
{
    static void Main( string[] args )
    {
        TestClass.q[ 0 ] = "I am not const";
        Console.WriteLine( TestClass.q[ 0 ] );
    }
}

You will need to find other ways to protect your array.