DEV Community

Vivek Nariya
Vivek Nariya

Posted on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
viveknariya profile image
Vivek Nariya

second

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay