Const Vs readonly in C#

In C#, both const and readonly are used to declare constants, but they have some key differences in terms of usage and behavior.

const

The const keyword is used to declare constants that have a fixed value at compile-time. The value of a const field is resolved at compile-time and cannot be changed at runtime. const fields are implicitly static and must be initialized at the time of declaration.

public class MyClass { public const int MaxValue = 100; // Error: Constants cannot be assigned a value dynamically or at runtime. // public const DateTime CurrentTime = DateTime.Now; }

In this example, the MaxValue field is a constant with a fixed value of 100. It cannot be modified or reassigned after declaration. Note that const fields are implicitly static, so they can be accessed using the class name (MyClass.MaxValue) rather than an instance of the class.

readonly

The readonly keyword is used to declare constants whose values can be assigned at runtime, typically within a constructor or initialization block. Unlike const, readonly fields allow for the assignment of values that are determined at runtime but cannot be modified after initialization. Each instance of the class can have a different value for readonly fields.

public class MyClass { public readonly int DefaultValue; public MyClass(int value) { DefaultValue = value; } }

In this example, the DefaultValue field is readonly and can be assigned a value within the constructor. Once assigned, the value cannot be changed. However, different instances of MyClass can have different values for DefaultValue.

Key Differences

  1. const fields are implicitly static, while readonly fields are instance-specific.
  2. const values are resolved at compile-time, while readonly values can be assigned at runtime.
  3. const fields must be assigned a value at the time of declaration, while readonly fields can be assigned a value within constructors or initialization blocks.

Conclusion

Choosing between const and readonly depends on the specific requirements of your application. Use const when the value is known and fixed at compile-time, and use readonly when the value needs to be assigned at runtime or when it depends on the instance.