DEV Community

Vivek Nariya
Vivek Nariya

Posted on

In C#, readonly and const are both used to define constants, but they have some key differences

const

1 . Scope

  • Constants are implicitly static and have a scope limited to the class or struct in which they are declared. They are essentially compile-time constants and can be accessed using the class or struct name.

2 . Mutability

  • Constants declared with the const keyword are implicitly static and cannot be changed after declaration. They are evaluated at compile time and remain constant throughout the program.

3 . Value Assignment

  • Values of const fields must be known at compile time. They can only be assigned primitive types, enums, or strings.

readonly

1 . Scope

  • readonly fields are instance-level constants. Each instance of the class or struct has its own copy of the readonly field, and they can have different values in different instances.

2 . Mutability

  • readonly fields can be assigned a value either at the time of declaration or in a constructor. Once assigned, their value cannot be changed. They are evaluated at runtime.

3 . Value Assignment

  • The value of a readonly field can be determined at runtime. It can be assigned either at the time of declaration or within a constructor.
public class ConstantsExample
{
    public const int ConstValue = 10; // Compile-time constant
    public readonly int ReadOnlyValue; // Runtime constant

    public ConstantsExample(int value)
    {
        ReadOnlyValue = value; // Assigning value in constructor
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Accessing const field
        Console.WriteLine(ConstantsExample.ConstValue); // Output: 10

        // Creating instances with different readonly values
        ConstantsExample instance1 = new ConstantsExample(20);
        ConstantsExample instance2 = new ConstantsExample(30);

        Console.WriteLine(instance1.ReadOnlyValue); // Output: 20
        Console.WriteLine(instance2.ReadOnlyValue); // Output: 30
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
viveknariya profile image
Vivek Nariya

second