CodeBlanks Logo Icon CodeBlanks

const and readonly

C# course · Intermediate · Lesson 33/116

Learn the difference between const and readonly.

const fields

A const (constant) field is an immutable value computed at compile time. Declaration: public const double Pi = 3.14;.

Const values are substituted at compile time; every reference to Pi is replaced with 3.14. So const fields can only take constant expressions; no method calls or runtime values. Const fields are implicitly static; accessed as ClassName.Pi.

readonly fields

A readonly field holds an immutable value set at runtime. Declaration: public readonly int Radius;. It can be assigned only where it is declared or inside a constructor; afterwards it cannot change.

Unlike const, readonly can take a runtime value like new DateTime(2024,1,1). It is also an instance member; each instance may have a different value. Use readonly when the value can't be computed at compile time or is per-instance.

Exercise Circle perimeter

Add public const double Pi = 3.14; and public readonly int Radius; to Circle. The constructor assigns this.Radius = radius;. The Perimeter method returns (int)(2 * Pi * Radius). In Main, create new Circle(5) and print the perimeter.

Show example solution
Add `public const double Pi = 3.14;` and `public readonly int Radius;` to Circle. In the ctor write `this.Radius = radius;`. In Perimeter write `return (int)(2 * Pi * Radius);`. In Main write `var c = new Circle(5); Console.WriteLine(c.Perimeter());`.
Example solution:
using System;

class Circle
{
    public const double Pi = 3.14;
    public readonly int Radius;

    public Circle(int radius)
    {
        this.Radius = radius;
    }

    public int Perimeter()
    {
        return (int)(2 * Pi * Radius);
    }
}

class Program
{
    static void Main()
    {
        var c = new Circle(5);
        Console.WriteLine(c.Perimeter());
    }
}

Test yourself

  1. Which statement about const is correct?

    • A const field can be assigned at runtime.
    • Const fields are implicitly static.
    • Const fields can be changed in a constructor.
    • Const fields can only be strings.
    Show answer

    Const fields are implicitly static. — Correct. Const fields are implicitly static; accessed through the class name.

  2. Fill in the blank: const declaration

    class MathConst
    {
        public const double Pi = ____;
    }
    Show answer
    class MathConst
    {
        public const double Pi = 3.14;
    }
  3. Match: const and readonly

    const
    compile-time constant
    readonly
    assigned in constructor
    const Pi
    implicitly static
    readonly Radius
    separate per instance

All lessons in Intermediate