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

后端 未结 5 544
你的背包
你的背包 2021-01-02 17:57

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,

相关标签:
5条回答
  • 2021-01-02 18:25

    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.

    0 讨论(0)
  • 2021-01-02 18:27

    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.

    0 讨论(0)
  • 2021-01-02 18:36

    C# is not allowed to write code directly into the classes; it is allowed to write only data members and function members directly into the classes.

    0 讨论(0)
  • You can also get this if you have punctuation issues, I got it today when I missing a simple parentheses:

    public static string GetPasswordForEnvironment)
    

    should have been:

    public static string GetPasswordForEnvironment()
    

    But the error showed up on the first "if" statement later in the function.

    0 讨论(0)
  • 2021-01-02 18:39

    C# does not provide writing the for, while or foreach kind of looping statement directly inside the class. These statements should be within a user defined method, main method or constructors.

      class Array
    {
        public static void main(string[] args)
        {
            int[] n = new int[10]; /* n is an array of 10 integers */
    
            /* initialize elements of array n */
            for (int i = 0; i < 10; i++)
            {
                n[i] = i + 100;
            }
    
            /* output each array element's value */
            foreach (int j in n)
            {
                int i = j - 100;
                Console.WriteLine("Element[{0}] = {1}", i, j);
            }
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题