Why can't I assign a value to a const int field? [closed]
-
01-07-2021 - |
Domanda
okay, so I have an int lets say called "Var1":
public const int Var1 = 0;
now I want to assign this to an Int32 value like so:
Var1 = Convert.ToInt32(Console.ReadLine());
It will then give me this error:
The left-hand side of an assignment must be a variable, property or indexer
Help? I'm new to this, sorry if this is a simple mistake.
Soluzione
The const
keyword means that the field is a constant and thus can only be assigned once: at declaration time.
You have assigned the value 0
, therefore you can't overwrite it with a new value later.
Remove the modifier to fix your problem.
Altri suggerimenti
Think about what you are doing there:
public const int Var1 = 0;
const
means CONSTANT. It means you cannot change it.
A const
is a constant; you cannot change its value at runtime (and the iNitial alum must be a constant expression evaluated at the compiler).
Just remove the const
and things should work:
public int Var1 = 0;
// ...
Var1 = Convert.ToInt32(Console.ReadLine());
Well, Var1 is declared as a const field, that means you cannot change its value. If you want to change the value of Var1, then you must remove the "const" qualifier.
You are declaring Var1
as const (which is quite an oxymoron in itself).
const
members cannot be modified, so they cannot be assigned to. If you want Var1
to be mutable, remove the const
modifier:
public int Var1 = 0;
Note that you do not need to explicitly initialize the member to 0
, since it is the default value of the int
type. You only have to write:
public int Var1;
I would also suggest making the member private
and exposing it to the outside world through a a public
property, which is considered as a better encapsulation practice:
private int _var1;
public int Var1
{
get {
return _var1;
}
set {
_var1 = value;
}
}