C# const vs readonly — Interview Questions
Q1. What’s the difference between const and readonly?
constis a compile-time constant and is implicitly static.readonlyis assigned at runtime during initialization or construction and cannot be reassigned afterward.
Why?
const represents a value the compiler can know; readonly represents runtime state that becomes fixed after initialization.
Q2. Why not just use private?
privatecontrols accessibility; it doesn’t prevent reassignment inside the class.
private string _name; // can change internally
private readonly string _name; // cannot reassign after constructionWhy?
private and readonly solve different problems: access control vs mutation control.
Q3. What’s the Java equivalent of readonly?
Java’s closest equivalent is
finalfor fields.
private final String name;private readonly string _name;Why?
Both allow initialization followed by no reassignment.
Q4. Can a readonly field have a setter?
No. A property setter cannot bypass the
readonlyrestriction.
If you want:
Outside → READ
Class → WRITEuse:
public string Name { get; private set; }Why?
private set controls property access, whereas readonly controls field reassignment.
Q5. Can get; private set; change after construction?
Yes, from inside the class.
public string Status { get; private set; }
public void Complete()
{
Status = "Completed"; // ✅
}Why?
private set allows the containing class to modify the property.
Q6. Can a readonly field reference a mutable object?
Yes.
private readonly List<string> _items = new();
_items.Add("A"); // ✅
_items = new(); // ❌Why?
readonly prevents changing the reference, not changing the referenced object’s contents.
Q7. When would you use static readonly instead of const?
When there should be one value for the type, but the value must be calculated or obtained at runtime.
public static readonly Guid ApplicationId = Guid.NewGuid();Why?
Guid.NewGuid() cannot be evaluated at compile time.
Q8. Give the Java → C# mapping.
Java C#
private final String name → private readonly string _name;
static final int MAX = 10 → const int Max = 10;
static final Guid id = → static readonly Guid Id =
UUID.randomUUID(); Guid.NewGuid();Why?
The first is write-once instance state, the second is a compile-time constant, and the third is a runtime-initialized class-level value.
30-second answer
“
privatecontrols who can access a field, whilereadonlycontrols whether the field can be reassigned.readonlyis roughly analogous to Java’sfinalfor fields.constis different because it is a compile-time constant and is implicitly static. I useconstfor genuine compile-time invariants,readonlyfor runtime values that should be fixed after construction, andget; private set;when the class needs controlled mutation.”