I have a seemingly basic problem with C# arrays. I am a beginner, but this is a really basic problem and it has had me in knots for more than half an hour now. I am using C# 2010 Express.
This code:-
string[] motionCam = new string[8];
motionCam[1] = "Stop";
Reports the error:
Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
Even basic array examples I copy and paste off of education web sites report this same error and I have no clue why.
The other answers that state that you cannot put that line of code in a class declaration but outside of a method body are correct. I thought it might be interesting to describe why you get the odd error message. The compiler is attempting desperately to try to figure out what you mean by X[Y] = Z;
, and it assumes that what you meant was:
X[] F = Z;
That is, that you accidentally put the size of the array in the array declaration -- a very common error amongst C programmers who have recently learned C# -- and have omitted the name of the field.
The compiler therefore gives the most informative error that it can come up with: that you are probably a C programmer who has forgotten that the size of the array goes in the initializer, not the type declaration.
In this case that guess is completely wrong; the error here is that you've accidentally put a statement where a field declaration is expected. But most of the time, that's a reasonable guess.
While the code you pasted is valid, your problem is something else.
Maybe you declared it in the class level.
motionCam[1] = "Stop";
is an assignment not a declaration, this why the compiler shouts.
See this question of someone who had that the same problem.
Bottom line is You can't have non-declaration statements at the class level.
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