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