Difference Between const and readonly in C#
Difference Between const and readonly in C#
In C#, both const and readonly are used to
declare values that should not change after assignment. However, they serve
different purposes and behave differently in key aspects such as initialization
timing, usage, and flexibility.
What is const?
- const
is short for constant.
- The
value must be assigned at compile time.
- It
is implicitly static, meaning it belongs to the type, not an instance.
- It
must be initialized at the time of declaration.
- Cannot
be changed anywhere else in the code.
Example:
public class
MyClass
{
public const double Pi = 3.14159;
}
What is readonly?
- readonly
means the value can only be assigned once, either at declaration or in a
constructor.
- It
can be used for instance-level or static data.
- Its
value can be determined at runtime.
- It
provides more flexibility than const.
Example:
public class
MyClass
{
public readonly int Id;
public MyClass(int id)
{
Id = id; // Can be set here
}
}
Comparison
Between const and readonly
Feature |
const |
readonly |
When value is assigned |
At compile time |
At runtime (declaration or constructor) |
Static |
Always |
Optional |
Can be set in constructor |
No |
Yes |
Can hold runtime data |
No |
Yes |
Allowed types |
Primitive, string, enum |
Any type |
Use case |
Fixed values like Pi, max limits |
Values that vary per instance or are
initialized dynamically |
Practical Use
Cases
Use const when:
- The
value never changes.
- The
value is known at compile time.
- You
want maximum performance and inlining by the compiler.
Use readonly when:
- The
value is only known at runtime.
- You
want to assign the value in the constructor.
- You
are working with complex types or need more flexibility.
Summary
Use const for compile-time constants, and readonly
for runtime-assigned but immutable values. Choosing the right keyword helps
ensure clarity, safety, and appropriate usage in the codebase.
Comments
Post a Comment