I cannot understand these 2 strange behaviour
1. First Behaviour
I have declared a variable like this
double[][] dd =
{
new double[10],
new double[10]
};
It does not give error.
But if i do like this it gives error
double[][] dd;
dd = { // Here it gives 2 errors says Invalid Expression { and ; expected
new double[10],
new double[10] //Here and in the above line it says only
//assignment, call, increment....can be used as a statement
};
Error is gone if i do this
double[][] dd;
dd = new double[][]{
new double[10],
new double[10]
};
Why?
2. Second Behaviour
More over it does not error if an extra comma , is put after last element of array in any of the above cases
{
new double[10],
new double[10], //This comma here is not given as error. Why?
};
Should that extra comma not specify that one more entity should be added after it.
Quite old docs, but still relevant. What you’re looking at are Array Initializers
Note, it doesn’t say that they’re available in assignment statements, which is what you’re attempting with your first error.
To your second question, the reason why the extra
,is allowed is convenience – it’s especially useful if code is being generated programmatically if you don’t have to special case the first or last item. You’ll find similar syntax in e.g. enum declarations.