Difference between constant and read-only in C# dot net
Loading
Difference between constant and read-only in C# dot net
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Saurabh PrajapatiRank #287 · 8.8K reputationPosted Jun 23, 2025, 1:35 AM EDT
Const is a compile-time constant, while
readonlyis assigned at runtime and cannot be changed afterward.Raja Musab Bin Khalid2 reputationPosted Jun 23, 2025, 3:53 PM EDT
Const are Constants, and its value is assigned at the time of compilation while readonly is runtime variable which is assign on runtime.
Both cannot be changed once assigned
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Jun 23, 2025, 10:42 PM EDT
https://www.c-sharpcorner.com/blogs/difference-between-constant-and-readonly
Sandhiya PriyaRank #26 · 43.2K reputationPosted Oct 27, 2025, 12:25 AM EDT
1. Definition
2. When the Value is Assigned
Example:
public class Demo { public const int ConstValue = 10; // compile-time constant public readonly int ReadOnlyValue; // runtime constant public Demo(int val) { ReadOnlyValue = val; // can be assigned here } }3. Changeability
4. Memory Behavior
5. Scope and Usage
Example:
public static readonly MyClass Obj = new MyClass(); // valid public const MyClass Obj = new MyClass(); // ? invalid6. Example Comparison
public class Example { public const int ConstValue = 100; // fixed at compile-time public readonly int ReadOnlyValue; public Example(int val) { ReadOnlyValue = val; // assigned at runtime } public void Display() { Console.WriteLine(ConstValue); // always 100 Console.WriteLine(ReadOnlyValue); // depends on constructor input } }Usage:
Example e1 = new Example(50); Example e2 = new Example(200); e1.Display(); // Const=100, ReadOnly=50 e2.Display(); // Const=100, ReadOnly=200Summary Table
Example Use Case
Use
constfor values that never change, likePI,DaysInWeek, etc.Use
readonlyfor values that depend on runtime input, like a config ID, database connection string, or environment setting.Jaimin ShethiyaRank #177 · 13.7K reputationPosted Oct 28, 2025, 8:18 AM EDT
Hello Kiran,
Please refer below article for more information.
Difference Between ReadOnly and Constant in .NET C#
Thanks