CodeBlanks Logo Icon CodeBlanks

Constants

C# course · Beginner · Lesson 9/116

Learn to declare immutable constants with the const keyword.

Constants with const

Some values never change during a program: the number pi, the days in a week, the maximum players in a game. For these you use const.

A const variable is set at compile time and cannot be changed afterwards. Example: const double Pi = 3.14;

A const must always be initialized: const int Max; is an error. You cannot assign its value later.

Constants are usually named in PascalCase: MaxScore, TaxRate, Pi.

The readonly difference

const and readonly are alike but serve different purposes. A const value is known at compile time and never changes.

A readonly value can be set at runtime; for example, a value read from a configuration file. It is set once and then never changes.

const works anywhere; readonly applies only to class fields, not to local variables.

Rule: pick const when the value is always the same, readonly when it is set once at runtime.

Exercise Compute remaining score with const

Declare const int MaxScore with 100. Declare int score with 75. Compute remaining as MaxScore - score. Print the result with Console.WriteLine.

Show example solution
Start with const int MaxScore = 100;, then add int score = 75; and int remaining = MaxScore - score;.
Example solution:
const int MaxScore = 100;
int score = 75;
int remaining = MaxScore - score;
Console.WriteLine(remaining);

Test yourself

  1. Keyword for a constant

    ____ double Pi = 3.14;
    Show answer
    const double Pi = 3.14;
  2. Which of the following is true?

    • const values can be changed later
    • const can be declared without initialization
    • const value is set at compile time
    • const can only be used at class level
    Show answer

    const value is set at compile time — Correct! A const value is set at compile time and never changes.

  3. Match each concept to its meaning

    const
    compile time
    readonly
    runtime
    constant
    fixed value
    field
    class member

All lessons in Beginner