Difference Between const and readonly in C#
🔍 Introduction
In C#, both const and readonly are used to declare unchangeable values. However, their use cases, behavior, and limitations differ significantly.
📌 What is const?
- Short for constant
- Value must be assigned at compile time
- Implicitly
static— shared across instances - Must be initialized at declaration
- Cannot be modified elsewhere
public class MyClass
{
public const double Pi = 3.14159;
}
📌 What is readonly?
- Value can be assigned at declaration or in constructor
- Can be instance-level or static
- Initialized at runtime
- More flexible than
const
public class MyClass
{
public readonly int Id;
public MyClass(int id)
{
Id = id; // Set only once
}
}
⚖️ Comparison: const vs readonly
| Feature | const | readonly |
|---|---|---|
| When value is assigned | Compile time | Runtime (declaration or constructor) |
| Static | Always | Optional |
| Set in constructor? | No | Yes |
| Supports runtime data? | No | Yes |
| Allowed types | Primitive, string, enum | Any type |
| Use case | Compile-time constants | Instance or dynamic values |
💼 Practical Use Cases
✅ Use const when:
- The value never changes
- It’s known at compile time
- Performance and inlining are important
✅ Use readonly when:
- The value is assigned at runtime
- You need constructor-based initialization
- You use complex types or objects
📌 Summary
Use const for fixed, compile-time values. Use readonly for flexible, runtime-assigned values that shouldn't change after initialization. Choosing the right one improves maintainability and safety in your C# code.

Comments
Post a Comment