Search code examples
c#intconstantsvariable-assignmentbuild-error

Why can't I assign a value to a const int field?


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.


Solution

  • 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.