+ 1
Access Modifiers(Can't assign integer value to variable)
(Btw, had to type this on my phone) Code: namespace Practice; { class Program { class Base { public int x; } class Base2: Base { x = 5; } } } Error: Invalid token '=' in class, struct, or interface Practice member declaration.
6 ответов
+ 2
You can't assign a variable like that. That's like writing this:
class ex{
int x;
x = 5; //ERROR
}
Assuming x was even declared before assigning it.
Assign the value of x in a method to fix. Perhaps a constructor would fit what you want.
+ 2
Yes you can 'access' it anywhere.
Notice the error isn't that x wasn't defined, the error is that you cannot assign x like that outside a function, or scruct etc.. if it's already been declared.
+ 2
That's inside a function though.
Assigning something is a statement.
All statements must be inside a block of code.
A classes block of code can have declarations, but not statements.
So you can initialize a variable outside a block of code (or only in a class) only on declaration. You cannot assign it on command anywhere. It must be in something that can have statements.
class a{
int a = 15; // 👌
int b;
b = 15; // NO
(In java)
int c;
{
c = 15; // 👌
}
}
+ 1
Oh ok I'm starting to get it now.
0
But since the integer 'x' is public, shouldn't I be able to use it whenever?
0
I can do it here though:
static void Main(string [] args)
{
int x;
x = 2;
}
What makes it different in a class?