C# const vs readonly — Interview Questions

Q1. What’s the difference between const and readonly?

const is a compile-time constant and is implicitly static. readonly is 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?

private controls accessibility; it doesn’t prevent reassignment inside the class.

private string _name;          // can change internally
private readonly string _name; // cannot reassign after construction

Why?

private and readonly solve different problems: access control vs mutation control.

Q3. What’s the Java equivalent of readonly?

Java’s closest equivalent is final for 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 readonly restriction.

If you want:

Outside → READ
Class   → WRITE

use:

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

private controls who can access a field, while readonly controls whether the field can be reassigned. readonly is roughly analogous to Java’s final for fields. const is different because it is a compile-time constant and is implicitly static. I use const for genuine compile-time invariants, readonly for runtime values that should be fixed after construction, and get; private set; when the class needs controlled mutation.”