Why wouldn't `new int[x]{}` be valid?
-
27-09-2019 - |
Question
In MonoDevelop I have the following code which compiles:
int[] row = new int[indices.Count]{};
However, at run-time, I get:
Matrix.cs(53,53): Error CS0150: A constant value is expected (CS0150) (testMatrix)
I know what this error means and forces me to then resize the array:
int[] row = new int[indices.Count]{};
Array.Resize(ref row, rowWidth);
Is this something I just have to deal with because I am using MonoDevelop on Linux? I was certain that under .Net 3.5 I was able to initialize an array with a variable containing the width of the array. Can anyone confirm that this is isolated? If so, I can report the bug to bugzilla.
Solution
You can't mix array creation syntax with object initialization syntax. Remove the { }
.
When you write:
int[] row = new int[indices.Count];
You are creating a new array of size indices.Count
initialized to default values.
When you write:
int[] row = new int[] { 1, 2, 3, 4 };
You are creating an array and then initializing it's content to the values [1,2,3,4]. The size of the array is inferred from the number of elements. It's shorthand for:
int[] row = new int[4];
row[0] = 1;
row[1] = 2;
row[2] = 3;
row[3] = 4;
The array is still first initialized to defaults, this syntax just provides a shorthand to avoid havind to write those extra assignments yourself.
OTHER TIPS
The following code fails to compile for the same reason on Windows/.NET/LINQPad:
void Main()
{
int[] row = new int[indices.Count]{};
row[2] = 10;
row.Dump();
}
// Define other methods and classes here
public class indices {
public static int Count = 5;
}
However, removing the object initialisation from the declaration ({}
) makes it work.
In C#, if you want to declare an empty array the syntax should be:
int[] row = new int[indices.Count];
Because when you to use use array initialization syntax AND specify the size of the array
int[] arr = new int[5]{1,2,3,4,5};
The size of the array is superfluous information. The compiler can infer the size from the initialization list. As others have said, you either create empty array:
int[] arr = new int[5];
or use the initialization list:
int[] arr = {1,2,3,4,5};