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 const keyword are implicitly static and are evaluated at compile-time.
  • Once assigned, the value of a const cannot be changed throughout the program's execution.
  • const can only be applied to fields and variables at the time of declaration.
  • const fields 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:

  • readonly fields can be assigned a value either at the time of declaration or within the constructor of the containing class.
  • Unlike const, readonly fields are evaluated at runtime.
  • readonly fields allow for a single assignment, but their value can vary based on conditions within the constructor.
  • readonly fields 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}");
    }
}
Featureconstreadonly
InitializationMust be initialized at declarationCan be initialized either at declaration or within the constructor
Data Types AllowedLimited to value types, strings, and constantsCan be used with any data type
ScopeLimited to compile-time constantsApplicable to instance or static fields
ModificationCannot be modified after declarationCan only be modified in the constructor or field initializer
UsageUsed for values that are known at compile-timeUsed 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.

c-sharp
const
readonly