{"id":56,"date":"2014-05-23T06:53:00","date_gmt":"2014-05-23T05:53:00","guid":{"rendered":"https:\/\/debuggersspace.com\/index.php\/2014\/05\/23\/what-is-difference-between-constants-and-read-only\/"},"modified":"2024-09-27T15:35:58","modified_gmt":"2024-09-27T14:35:58","slug":"what-is-difference-between-constants-and-read-only","status":"publish","type":"post","link":"https:\/\/debuggersspace.com\/index.php\/2014\/05\/23\/what-is-difference-between-constants-and-read-only\/","title":{"rendered":"Difference Between const and readonly in C#"},"content":{"rendered":"<div class='booster-block booster-read-block'>\n                <div class=\"twp-read-time\">\n                \t<i class=\"booster-icon twp-clock\"><\/i> <span>Read Time:<\/span>4 Minute, 15 Second                <\/div>\n\n            <\/div><p>In C#, both <code>const<\/code> and <code>readonly<\/code> are used to define variables whose values cannot be changed after assignment. However, there are significant differences between the two in terms of behavior, usage, and when the value is assigned.<\/p>\n<h3>1. Declaration and Initialization<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>:\n<ul>\n<li>Must be declared and initialized at the time of declaration.<\/li>\n<li>The value is fixed at compile time and cannot be changed later.<\/li>\n<li><code>const<\/code> is implicitly <code>static<\/code>, meaning it belongs to the type, not the instance.<\/li>\n<li>Can only hold primitive types, enums, or strings.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>:\n<ul>\n<li>Can be initialized either at the time of declaration or in the constructor of the class.<\/li>\n<li>The value is set at runtime and can vary depending on the constructor used.<\/li>\n<li><code>readonly<\/code> variables can be instance-level (non-static) or static.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h4>Examples:<\/h4>\n<pre><code>\r\n\/\/ const\r\npublic const int MaxValue = 100;  \/\/ Must be initialized at declaration\r\n\r\n\/\/ readonly\r\npublic readonly int MaxValue;\r\npublic MyClass() {\r\n    MaxValue = 100;  \/\/ Initialized in the constructor\r\n}\r\n<\/code><\/pre>\n<h3>2. Value Assignment<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>:\n<ul>\n<li>Value is assigned at <strong>compile time<\/strong>.<\/li>\n<li>Cannot assign a value after declaration, and it is substituted directly into the compiled code.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>:\n<ul>\n<li>Value is assigned at <strong>runtime<\/strong>.<\/li>\n<li>Can be assigned in the constructor and can vary depending on the instance or constructor logic.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3>3. Usage<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>: Used for values known at compile time and will never change (e.g., mathematical constants, app settings).<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>: Used for values that may not be known until runtime (e.g., configurations, input-based values).<\/li>\n<\/ul>\n<h4>Examples:<\/h4>\n<pre><code>\r\n\/\/ const usage\r\npublic const double Pi = 3.14159;  \/\/ Known value at compile time\r\n\r\n\/\/ readonly usage\r\npublic readonly int RuntimeValue;\r\npublic MyClass(int value) {\r\n    RuntimeValue = value;  \/\/ Assigned during runtime\r\n}\r\n<\/code><\/pre>\n<h3>4. Static Context<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>: Implicitly <code>static<\/code> and belongs to the type, not the instance.<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>: Can be either instance-level or <code>static<\/code>. A <code>static readonly<\/code> can be assigned in a static constructor.<\/li>\n<\/ul>\n<h4>Examples:<\/h4>\n<pre><code>\r\n\/\/ const (implicitly static)\r\npublic const int MaxConnections = 100;\r\n\r\n\/\/ static readonly\r\npublic static readonly string AppName;\r\nstatic MyClass() {\r\n    AppName = \"My Application\";  \/\/ Set at runtime in static constructor\r\n}\r\n<\/code><\/pre>\n<h3>5. Flexibility<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>:\n<ul>\n<li>Less flexible as they must be initialized at compile time.<\/li>\n<li>Can only be used with basic types (e.g., <code>int<\/code>, <code>string<\/code>, <code>double<\/code>).<\/li>\n<\/ul>\n<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>:\n<ul>\n<li>More flexible since the value can be set at runtime.<\/li>\n<li>Can hold complex types such as objects, arrays, and collections.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h4>Example:<\/h4>\n<pre><code>\r\n\/\/ readonly with complex types\r\npublic readonly DateTime CreatedAt;\r\npublic MyClass() {\r\n    CreatedAt = DateTime.Now;  \/\/ Set during runtime\r\n}\r\n<\/code><\/pre>\n<h3>6. Memory Efficiency<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>:\n<ul>\n<li>Stored as part of the metadata in the compiled assembly.<\/li>\n<li>The value is substituted directly into the code wherever it\u2019s used, leading to efficient memory usage but possible versioning issues if a library changes a constant value.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>:\n<ul>\n<li>Stored as fields in memory, like normal variables.<\/li>\n<li>Because they are not substituted directly into the code, versioning issues are avoided.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h3>Real-World Analogy<\/h3>\n<ul>\n<li><strong>Constants (<code>const<\/code>)<\/strong>: Think of a birthdate. It is fixed and cannot change. Once set, it stays the same for the rest of your life.\n<pre><code>public const string Birthdate = \"January 1, 1990\";<\/code><\/pre>\n<\/li>\n<li><strong>Read-Only (<code>readonly<\/code>)<\/strong>: Think of an ID card number. It is assigned at some point in time (when the card is issued) but cannot change afterward.\n<pre><code>public readonly string IDNumber;\r\npublic Person(string id) {\r\n    IDNumber = id;  \/\/ Set when issued\r\n}\r\n<\/code><\/pre>\n<\/li>\n<\/ul>\n<h3>Key Differences<\/h3>\n<table style=\"width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 16px; text-align: left;\">\n<thead>\n<tr style=\"background-color: #f2f2f2;\">\n<th style=\"border: 1px solid #ddd; padding: 12px;\">Feature<\/th>\n<th style=\"border: 1px solid #ddd; padding: 12px;\"><code>const<\/code><\/th>\n<th style=\"border: 1px solid #ddd; padding: 12px;\"><code>readonly<\/code><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Initialization<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Must be initialized at declaration<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Can be initialized at declaration or in constructor<\/td>\n<\/tr>\n<tr style=\"background-color: #f9f9f9;\">\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Assignment<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Assigned at compile time<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Assigned at runtime<\/td>\n<\/tr>\n<tr>\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Modification<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Cannot be modified after declaration<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Cannot be modified after initialization<\/td>\n<\/tr>\n<tr style=\"background-color: #f9f9f9;\">\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Types Allowed<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Primitive types, strings, enums<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">All types, including complex types<\/td>\n<\/tr>\n<tr>\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Implicitly Static<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Yes<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">No (must be declared <code>static<\/code>)<\/td>\n<\/tr>\n<tr style=\"background-color: #f9f9f9;\">\n<td style=\"border: 1px solid #ddd; padding: 12px;\"><strong>Usage<\/strong><\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Used for constants known at compile time<\/td>\n<td style=\"border: 1px solid #ddd; padding: 12px;\">Used for values determined at runtime<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Important and Tricky Q&amp;A<\/h3>\n<h4>Q1: Can a <code>const<\/code> be assigned a value in a constructor?<\/h4>\n<p><strong>Answer<\/strong>: No, <code>const<\/code> values must be assigned at the time of declaration, and they cannot be changed later. They are set at compile time.<\/p>\n<h4>Q2: Can a <code>readonly<\/code> value be changed after initialization in the constructor?<\/h4>\n<p><strong>Answer<\/strong>: No, once a <code>readonly<\/code> value is initialized in the constructor, it cannot be modified afterward.<\/p>\n<h4>Q3: Why would you choose <code>readonly<\/code> over <code>const<\/code>?<\/h4>\n<p><strong>Answer<\/strong>: Choose <code>readonly<\/code> when you need to set the value at runtime (e.g., based on constructor logic or external input) or when working with non-primitive types. Use <code>const<\/code> when the value is constant and known at compile time.<\/p>\n<h4>Q4: Can <code>readonly<\/code> be <code>static<\/code>?<\/h4>\n<p><strong>Answer<\/strong>: Yes, <code>readonly<\/code> can be either instance-level or <code>static<\/code>. If it\u2019s static, the value is shared across all instances and can only be assigned in a static constructor.<\/p>\n<h4>Q5: Can <code>const<\/code> be used for complex types like arrays or objects?<\/h4>\n<p><strong>Answer<\/strong>: No, <code>const<\/code> can only be used for primitive types, strings, and enums. Use <code>readonly<\/code> if you need to work with complex types like objects or arrays.<\/p>\n<h3>Conclusion<\/h3>\n<p>Use <strong><code>const<\/code><\/strong> when the value is fixed at compile time and will never change. Use <strong><code>readonly<\/code><\/strong> when the value is determined at runtime but should not be modified afterward. Understanding the differences between these two is crucial for writing maintainable and efficient code in C#.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In C#, both const and readonly are used to define variables whose values cannot be changed after assignment. However, there are significant differences between the two in terms of behavior, usage, and when the value is assigned. 1. Declaration and Initialization Constants (const): Must be declared and initialized at the time of declaration. The value [&hellip;]<\/p>\n","protected":false},"author":43,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","footnotes":""},"categories":[23,24,188,161],"tags":[201,200],"class_list":["post-56","post","type-post","status-publish","format-standard","hentry","category-asp-net","category-c-net","category-technical-explorations","category-top-100-qa","tag-constants","tag-readonly"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Himanshu Namdeo","author_link":"https:\/\/debuggersspace.com\/author\/admin\/"},"uagb_comment_info":0,"uagb_excerpt":"In C#, both const and readonly are used to define variables whose values cannot be changed after assignment. However, there are significant differences between the two in terms of behavior, usage, and when the value is assigned. 1. Declaration and Initialization Constants (const): Must be declared and initialized at the time of declaration. The value&hellip;","_links":{"self":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/56"}],"collection":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/users\/43"}],"replies":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/comments?post=56"}],"version-history":[{"count":2,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/56\/revisions"}],"predecessor-version":[{"id":809,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/56\/revisions\/809"}],"wp:attachment":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/media?parent=56"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/categories?post=56"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/tags?post=56"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}