Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a static readonly array, but the values are calculated at build time

Is there a way I can create a static array with readonly values, but using some logic to create it? Let me try to explain:

I know I can do this:

public static readonly int[] myArray = { 1, 2, 3 };

but is it possible to do something like:

public static readonly int[] myArray2 = 
{
    for (int i = 0; i < 256; i++)
    {
        float[i] = i;
    }
};

EDITED: A good solution to my question: Static Constructor! http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=VS.100%29.aspx :D

like image 774
Pedro77 Avatar asked Sep 15 '11 14:09

Pedro77


People also ask

What is difference between static const and read only?

The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.

Are readonly variables static?

The keyword readonly has a value that may be changed or assigned at runtime, but only through the non-static constructor. There isn't even a method or static method.

What is private static readonly in C#?

A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.

What is difference between constant and readonly in C#?

ReadOnly Vs Const Keyword In C#, constant fields are created using const keyword. ReadOnly is a runtime constant. Const is a compile time constant. The value of readonly field can be changed.


1 Answers

What you can do is:

public class YourClass
{
    public static readonly int[] myArray2 = null;

    static YourClass()
    {
        myArray2 = new int[256];
        for (int i = 0; i < 256; i++)
        {
            myArray2 [i] = i;
        }        
    }
}

Or:

public static readonly int[] myArray2 = Enumerable.Range(0, 255).ToArray();
like image 126
Arnaud F. Avatar answered Sep 28 '22 05:09

Arnaud F.