CodeBlanks Logo Icon CodeBlanks

const vs readonly

C# course · Intermediate · Lesson 38/116

Learn the usage differences between const and readonly.

Constants vs readonly

const and readonly are similar but serve different needs. const takes its value at compile time, readonly at runtime.

const values are embedded into consumers; another assembly that uses it copies the value. So changing a const forces recompiling the consumers. readonly is read from a single source every time; when the value changes, only the declaring assembly needs updating. This matters in public APIs.

Versioning impact

const's embedding behavior creates versioning issues. For example, public const int MaxSize = 10; is written into another assembly as 10. If you change MaxSize to 20 and publish only the declaring assembly, the consumer keeps using the old 10.

That's why public APIs prefer static readonly: the value is read from a single source every time, and updates propagate instantly. const is safe for internal constants.

Exercise Settings class

Add public const string AppName = "Quiz"; and public readonly DateTime BuildDate; to Settings. The constructor should assign this.BuildDate = buildDate;. In Main, create new Settings(new DateTime(2024, 1, 15)) and print Settings.AppName and BuildDate.Year.

Show example solution
Add `public const string AppName = "Quiz";` and `public readonly DateTime BuildDate;` to Settings. In the ctor write `this.BuildDate = buildDate;`. In Main write `var s = new Settings(new DateTime(2024, 1, 15)); Console.WriteLine(Settings.AppName); Console.WriteLine(s.BuildDate.Year);`.
Example solution:
using System;

class Settings
{
    public const string AppName = "Quiz";
    public readonly DateTime BuildDate;

    public Settings(DateTime buildDate)
    {
        this.BuildDate = buildDate;
    }
}

class Program
{
    static void Main()
    {
        var s = new Settings(new DateTime(2024, 1, 15));
        Console.WriteLine(Settings.AppName);
        Console.WriteLine(s.BuildDate.Year);
    }
}

Test yourself

  1. Match: const vs readonly

    const
    compile time
    readonly
    runtime
    const embedding
    consumers must recompile
    readonly instance
    may differ per instance
  2. Which statement about constants is correct?

    • const is computed at runtime.
    • readonly is implicitly static.
    • const never changes but readonly is assigned in the constructor.
    • const and readonly are exactly the same.
    Show answer

    const never changes but readonly is assigned in the constructor. — Correct. const never changes; readonly is assigned in the ctor and stays constant afterwards.

  3. Fill in the blank: runtime value

    class Settings
    {
        public readonly DateTime BuildDate = ____;
    }
    Show answer
    class Settings
    {
        public readonly DateTime BuildDate = new DateTime(2024, 1, 15);
    }

All lessons in Intermediate