Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and use arrays in C#

Tags:

arrays

c#

.net

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.

like image 218
Openstar63 Avatar asked Nov 29 '22 09:11

Openstar63


2 Answers

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.

like image 91
Eric Lippert Avatar answered Dec 11 '22 05:12

Eric Lippert


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.

like image 39
gdoron is supporting Monica Avatar answered Dec 11 '22 05:12

gdoron is supporting Monica