Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between readonly and const keyword in C#
In C#, both readonly and const are used to create fields whose values cannot be modified after being set. The key difference is when the value is determined − const is resolved at compile time, while readonly is resolved at runtime (in the constructor).
const Keyword
The const keyword creates a compile-time constant. The value must be assigned at the time of declaration and cannot be changed afterward. const fields are implicitly static and can be declared inside methods.
readonly Keyword
The readonly keyword creates a runtime constant. The value can be assigned either at declaration or inside a constructor, allowing different instances to have different values. readonly fields cannot be declared inside methods.
Key Differences
| Feature | const | readonly |
|---|---|---|
| Resolved At | Compile time | Runtime |
| Assignment | Must assign at declaration only | At declaration or in constructor |
| Value Change | Never (fixed at compile time) | Only in constructor (once) |
| Static/Instance | Implicitly static | Instance-level (can vary per object) |
| In Methods | Can be declared inside methods | Cannot be declared inside methods |
| Data Types | Only primitive and string types | Any data type including objects |
Example
The following example demonstrates both keywords ?
using System;
public class Program {
// const: must be assigned here, implicitly static
public const int MAX_VALUE = 10;
// readonly: can be assigned in constructor
public readonly int instanceValue;
Program(int value) {
instanceValue = value; // OK: assigned in constructor
}
public static void Main() {
// const accessed via class name (static)
Console.WriteLine("const MAX_VALUE: " + MAX_VALUE);
// readonly can differ per instance
Program p1 = new Program(11);
Program p2 = new Program(22);
Console.WriteLine("readonly p1: " + p1.instanceValue);
Console.WriteLine("readonly p2: " + p2.instanceValue);
}
}
The output of the above code is ?
const MAX_VALUE: 10 readonly p1: 11 readonly p2: 22
Notice how const has a single fixed value, while readonly allows each instance to have a different value assigned through the constructor.
Conclusion
Use const for values that are truly constant and known at compile time (like mathematical constants or fixed configuration). Use readonly for values that are determined at runtime and may vary between instances (like configuration loaded from a file or values passed to a constructor).
