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?


public class MyClass
{
    public const double Pi = 3.14159;
}
  

📌 What is readonly?


public class MyClass
{
    public readonly int Id;

    public MyClass(int id)
    {
        Id = id; // Set only once
    }
}
  

⚖️ Comparison: const vs readonly

Featureconstreadonly
When value is assignedCompile timeRuntime (declaration or constructor)
StaticAlwaysOptional
Set in constructor?NoYes
Supports runtime data?NoYes
Allowed typesPrimitive, string, enumAny type
Use caseCompile-time constantsInstance or dynamic values

💼 Practical Use Cases

✅ Use const when:

✅ 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

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features