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.
Exercise 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.
Show example solution
Add `public readonly int Id;` and `public readonly string Name;` to User. In the ctor write `this.Id = id;` and `this.Name = name;`. In Main write `var u = new User(1, "Alex"); Console.WriteLine(u.Id); Console.WriteLine(u.Name);`.
Example solution:
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);
}
}
Test yourself
-
Which statement about readonly is FALSE?
- A readonly field is assigned in a constructor.
- A readonly field can take a runtime value.
- A readonly field can differ per instance.
- A readonly field takes a compile-time value.
Show answer
A readonly field takes a compile-time value. — Correct (false statement). A readonly takes a runtime value, not a compile-time one.
-
Fill in the blank: readonly declaration
class User { public ____ int Id; }Show answer
class User { public readonly int Id; } -
Match: readonly properties
- assignment site
- constructor
- value type
- runtime
- instance copy
- separate per object
- later mutation
- forbidden