Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid token 'while' in class, struct, or interface member declaration in very simple code

I am not sure what the problem is but I keep receiving this error when I try to use a while statement in my code.

Invalid token 'while' in class, struct, or interface member declaration

I want to use a while loop to have something continuously update while a statement is true.

The rest of my code is rather long but whenever I type in the syntax:

while(a<b)
{
//do whatever i want it to do here
}

It gives me that compiler error right off the bat. Not quite sure what the problem is. I am doing this in a C# windows application under the Form1.cs file with all the other event handlers (for buttons and such). Thanks!


I was unaware that loops had to be placed within a method (fairly new to c#), but I tried it and no errors were returned. Thanks for your help everybody!

Previously, I just had the loop within the main class of the program.

like image 615
Eric Avatar asked Dec 29 '08 02:12

Eric


2 Answers

Based on the error, it sounds like the compiler thinks this code is typed directly in the body of a class/struct/interface declaration. Statements while/if/for/etc ... must appear with in a method.

Try moving this code into a method to fix the problem. If it's in a method, you likely have a mismatched brace problem.

like image 63
JaredPar Avatar answered Oct 18 '22 19:10

JaredPar


There's nothing wrong with the while, it's something above it that's the problem. Check for mismatched braces and semicolons in a comment or something like that.

like image 3
stu Avatar answered Oct 18 '22 19:10

stu