Reputation: 33
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
}
Upvotes: 0
Views: 195
Reputation: 2777
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
}
Upvotes: 3
Reputation: 61339
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"
Upvotes: 2