What is difference between const and readonly?
π‘ Concept: const vs readonly in C#
const and readonly are keywords used to define immutable values, but differ in when and how their values are assigned and used.
π Quick Intro
const is a compile-time constant; readonly is a runtime constant assigned once, typically in constructor.
π§ Analogy
Think of const as a tattooβpermanent and unchangeable; readonly as a signed contractβset once and fixed afterward.
π§ Technical Explanation
- const values are embedded at compile time; readonly values assigned at runtime.
- const must be assigned where declared; readonly can be assigned in constructor.
- const is static by default; readonly can be instance-level or static.
- const only supports primitive types and strings.
- readonly can hold reference types and complex objects.
π― Use Cases
- β Use const for fixed values known at compile time.
- β Use readonly for values assigned once during object construction.
- β Use readonly for complex types needing runtime initialization.
- β Use const for performance benefits in embedded values.
π» Code Example
public class Example {
public const double Pi = 3.1415;
public readonly int MaxValue;
public Example(int max) {
MaxValue = max;
}
}

β Interview Q&A
Q1: What is the difference between const and readonly?
A: const is compile-time, readonly is runtime.
Q2: Can readonly be assigned multiple times?
A: No, only once in constructor or declaration.
Q3: Are const values static?
A: Yes, implicitly static.
Q4: Can readonly hold complex objects?
A: Yes.
Q5: Can const be changed at runtime?
A: No.
Q6: Is readonly slower than const?
A: Slightly, due to runtime assignment.
Q7: Can const be instance level?
A: No, always static.
Q8: Can readonly be static?
A: Yes.
Q9: When to prefer readonly?
A: When value known only at runtime.
Q10: Are const and readonly thread-safe?
A: Yes, inherently immutable.
π MCQs
Q1. What is const in C#?
- Runtime constant
- Compile-time constant
- Variable
- Property
Q2. What is readonly in C#?
- Runtime constant
- Compile-time constant
- Variable
- Method
Q3. Can readonly be assigned multiple times?
- Yes
- No
- Sometimes
- Always
Q4. Are const values static?
- No
- Yes
- Maybe
- Sometimes
Q5. Can readonly hold complex objects?
- No
- Yes
- Maybe
- Sometimes
Q6. Can const be changed at runtime?
- Yes
- No
- Sometimes
- Rarely
Q7. Is readonly slower than const?
- Faster
- Slightly
- Same
- No
Q8. Can const be instance level?
- Yes
- No
- Maybe
- Sometimes
Q9. Can readonly be static?
- No
- Yes
- Sometimes
- Never
Q10. Are const and readonly thread-safe?
- No
- Yes
- Sometimes
- Never
π‘ Bonus Insight
Understanding const vs readonly helps write safer and more predictable C# code.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!