08 Feb 2024
Intermediate
In C#, both const and readonly are used to declare constants, but they differ in terms of when and how their values are assigned and how they can be used.
const Keyword:
- Constants declared using the
constkeyword are implicitlystaticand are evaluated at compile-time. - Once assigned, the value of a
constcannot be changed throughout the program's execution. constcan only be applied to fields and variables at the time of declaration.constfields are implicitly static, so they belong to the type, not to instances of the type.
public class ConstantsExample
{
// Declaring a constant field
public const int MaxValue = 100;
public void DisplayMaxValue()
{
// You can directly use a constant
Console.WriteLine($"The maximum value is: {MaxValue}");
}
}
readonly Keyword:
readonlyfields can be assigned a value either at the time of declaration or within the constructor of the containing class.- Unlike
const,readonlyfields are evaluated at runtime. readonlyfields allow for a single assignment, but their value can vary based on conditions within the constructor.readonlyfields can be instance-level or static.
public class ReadOnlyExample
{
// Declaring a readonly field
public readonly int MaxAttempts;
// Constructor to initialize readonly field
public ReadOnlyExample(int maxAttempts)
{
MaxAttempts = maxAttempts;
}
public void DisplayMaxAttempts()
{
Console.WriteLine($"The maximum attempts allowed is: {MaxAttempts}");
}
}
| Feature | const | readonly |
|---|---|---|
| Initialization | Must be initialized at declaration | Can be initialized either at declaration or within the constructor |
| Data Types Allowed | Limited to value types, strings, and constants | Can be used with any data type |
| Scope | Limited to compile-time constants | Applicable to instance or static fields |
| Modification | Cannot be modified after declaration | Can only be modified in the constructor or field initializer |
| Usage | Used for values that are known at compile-time | Used for values that are not known at compile-time, but that should not change after initialization |
In summary, the key differences between const and readonly in C# are related to when and how their values are assigned and whether the assignment happens at compile-time (const) or runtime (readonly). Use const for values that won't change and are known at compile-time, and use readonly for values that may change depending on conditions during runtime but still need to be set only once.