In C#, there are distinct rules for how const
and readonly
are applied, which explains why you encountered issues using them as you did in the code.
-
const
:
- Constant values (
const
) must be assigned a value that can be fully determined at compile-time. Therefore, you can only useconst
for primitive types likeint
,string
, or other simple types where the value is known at compile-time. - For example
const string s = "10"; // This is OK because the value "10" is known at compile time.
However, arrays or objects cannot be declared as const
, because the runtime memory for objects or arrays is allocated dynamically, and the array values are not known at compile-time.
const string[] summaries = { "Freezing", "Bracing", "Chilly" }; // Wrong!
-
readonly
:
- Readonly fields can only be assigned a value once during initialization (in the constructor or at declaration). The value can be set at runtime, unlike
const
, but it cannot be changed after being set. - The keyword
readonly
can only be used for class-level fields, meaning you cannot declare local variables inside a method asreadonly
.
readonly int a = 10; // Wrong! 'readonly' cannot be used in methods.
What's allowed:
- You can use
const
for compile-time constants of simple types (e.g.,int
,string
). - You can use
readonly
for instance fields but not for local variables inside a method.
Corrected version:
namespace ConsoleApp1
{
internal class Program
{
// Correct use of 'readonly' as a field (not inside a method)
private static readonly string[] summaries =
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
// Correct use of 'const' for compile-time constants
private const string s = "10";
static void Main(string[] args)
{
}
static void Summary()
{
// You can declare 'const' inside the method
const string methodString = "Sample string"; // OK
// 'readonly' cannot be used for local variables inside a method.
}
}
}
Key Differences:
-
const
applies to compile-time constants (simple types likeint
orstring
). -
readonly
applies to class-level fields that can be assigned a value at runtime but remain immutable once set.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin