CodeBlanks Logo Icon CodeBlanks

readonly fields

Learn runtime constants with readonly.

readonly fields

A readonly field is an immutable member set at runtime. Declaration: public readonly int Id;. It can be assigned only at its declaration or in the class's constructors; 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. Because it does not change after the constructor, readonly provides immutability.

When to use readonly?

readonly suits fields whose value must not change after construction but is determined by the constructor. Example: a User object's Id and CreatedAt fields come from the constructor and never change.

Similarly, an Order class's OrderDate field is set to DateTime.Now in the constructor and made readonly. This prevents accidental later changes. Per-instance values cannot be const; readonly is the natural choice.

Practice User model

Add public readonly int Id; and public readonly string Name; to User. The constructor should assign them with this.Id = id; and this.Name = name;. In Main, create new User(1, "Alex") and print Id and Name.

Starter code

Program.cs
using System;

class User
{
    // Add Id readonly field (int)
    
    // Add Name readonly field (string)

    public User(int id, string name)
    {
        // Assign Id and Name from ctor
    }
}

class Program
{
    static void Main()
    {
        // Create a user and print the fields
    }
}

Sample solution

Program.cs
using System;

class User
{
    public readonly int Id;
    public readonly string Name;

    public User(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
}

class Program
{
    static void Main()
    {
        var u = new User(1, "Alex");
        Console.WriteLine(u.Id);
        Console.WriteLine(u.Name);
    }
}

Expected output

1
Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which statement about readonly is FALSE?

  • A readonly field is assigned in a constructor.
  • A readonly field takes a compile-time value. Correct answer
  • A readonly field can differ per instance.
  • A readonly field can take a runtime value.

Explanation: (false statement). A readonly takes a runtime value, not a compile-time one.

2 Fill in the blank: readonly declaration

Question
class User
{
    public ____ int Id;
}
Answer
class User
{
    public readonly int Id;
}

Explanation: `readonly int Id` declares an immutable field assigned in the ctor.

3 Match: readonly properties

Term Meaning
assignment site constructor
value type runtime
instance copy separate per object
later mutation forbidden

All lessons in Intermediate