简体   繁体   中英

Why do I get the “name does not exist in current context” error even though I'm using name in the same scope as its declaration

I'm new to C# and trying to understand how things work. Why do I get the "name does not exist in current context" error even though I'm using name in the same scope as its declaration? Here is my code:

public class GradeBook
    {
        protected List<float> grades;

        public event NameChangedDelegate NameChanged;

        private string _name;

       _name = "blah"; //<---error happens here

       //more code
    }

You've got code not inside a class method inside of your class definition.

public class GradeBook
    {
        protected List<float> grades;

        public event NameChangedDelegate NameChanged;

        private string _name;

       void someMethod() {
          _name = "blah";
       }

       //more code
    }
  • or - as @dan says

Executable code (alternatively put, instructions, expressions, or more rigorously; statements) cannot exist "in a vacuum" in C#.

For example, in the class scope you can only have variable declarations and methods. _variable = "blah" is not allowed .

That code must reside in some method. Alternatively, if you just want to initialize the member you can do so inline:

private string _name = "blah"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM