C# Constants

Sometimes you have a value that should never change while your program runs, such as the number of days in a week or a fixed tax rate. C# lets you protect these values with the const keyword so they can never be accidentally reassigned.

Creating a Constant

A constant is declared just like a variable, but you add the const keyword in front of the type. Once a constant is given a value, that value is locked in for the life of the program. If you try to change it later, your code will not even compile.

Declaring a constant

const int daysInWeek = 7;
const double pi = 3.14159;

Console.WriteLine(daysInWeek);   // Outputs: 7
Console.WriteLine(pi);           // Outputs: 3.14159

Why Use Constants?

Constants make your code safer and easier to read. When you give a fixed value a clear name, anyone reading your code understands its meaning, and the compiler guarantees the value cannot be tampered with by mistake.

  • Protection: the compiler blocks any attempt to reassign the value.
  • Readability: a named constant like maxLoginAttempts is clearer than a bare number.
  • Maintainability: if a fixed value ever needs updating, you change it in one place.
  • Intent: it signals to other developers that this value is meant to stay the same.

Constants Must Be Assigned Immediately

Unlike a normal variable, you cannot declare a constant and fill it in later. The value has to be known at compile time and provided on the same line. The following example shows what is allowed and what is not.

Constants cannot be reassigned

const string appName = "Hyring";
Console.WriteLine(appName);

// appName = "NewName";   // Error: cannot reassign a constant
// const int limit;       // Error: must assign a value now
Note: By convention many C# developers write constant names in PascalCase, such as MaxItems or DaysInWeek, though camelCase is also common for local constants. Consistency within a project matters more than the exact style.

const vs readonly

C# also has a keyword called readonly. A const value is fixed when the code is compiled, while a readonly field can be set once at runtime, for example inside a constructor. For beginners, const is the tool you will reach for most, but it is good to know readonly exists for values that are only known when the program actually runs.

KeywordValue setCan vary per object
constAt compile timeNo
readonlyAt runtime, onceYes