Readonly vs const in C#: Understand the Key difference between readonly and const keyword in C#

The main difference between readonly and const keywords in C# lies in their assignment. Const must be defined at the time of declaration, whereas we can define readonly fields during runtime.
Additionally, const is implicitly static, whereas readonly values don’t necessarily have to be static. Regarding assembly behavior, constants are embedded into the IL code of every assembly that uses them, whereas readonly fields are shared between assemblies.

This article will look at the differences between the readonly and const keywords in C# and when to use each.

difference between readonly and const keyword in c#
Difference between readonly and const keywords in c#

What is readonly in C#?

The readonly is a keyword used to declare a variable whose value can be set only during initialization or in the constructor in the same class and cannot be changed after that. Each instance of the class holds its separate value for the readonly field, thus allowing each instance to have a unique value.

Example: ReadOnly in C#

Let’s take an example of the readonly keyword in C#.

using System;
class Person
{  
 // Declare a readonly field
    public readonly int age = 18;
    public Person() // Constructor
    {
        age = 22;
    }
    static void Main(string[] args)
    {
        Person obj = new Person();
        Console.WriteLine(obj.age); // Output: 22
    }
}

In the above code, age is declared as a readonly variable with a value of 18. However, its value can be changed to 22 in the constructor.

What is const in C#?

The keyword “const” is used for declaring a fixed value that remains unchanged during the entire execution of a program. The value assigned to a constant is determined during the compilation phase and cannot be changed during runtime. In simple words, When you declare a variable as const, you are telling the compiler that the value of this variable will never change.

A constant variable is a readonly variable, but the value is determined at the time of compilation and stored in the assembly metadata. Constants are frequently used for values identified during compilation time and do not change at runtime, such as mathematical constants or enumeration values.

For example, if you have a mathematical constant such as π (pi), you should declare it as a constant:

Example: Const keyword in C#

Let’s take an example of the Constant keyword in C#.

using System;
class Program
{
    const double PI = Math.PI;// using const keyword
    static void Main(string[] args)
    {
        Console.WriteLine(PI); //Output: 3.14159265358979
    }
}

During the compilation process, the value of constant fields is saved within the DLL or EXE file and can be viewed using the ILDASM tool.

Const keyword in csharp
Const keyword in C#
  • The const keyword is used to declare a constant value that we cannot change during the execution of a program.
  •  The readonly keyword is used to declare variables that we can initialize only once, either during declaration time or in a constructor.

Difference between readonly and const keyword in C#

01. Modification:

  • We cannot change the “const” keyword values once they are assigned.
  • The “readonly” keyword values can only be assigned once at the declaration time or in a constructor and cannot be modified afterward.

02. Initialization:

  • We must initialize the “const” keyword values at the declaration.
  • We can initialize the “readonly” keyword values either at the declaration or in a constructor.

03. Memory allocation:

  • The “const” keyword values are stored in memory as a part of the program’s metadata.
  • The “readonly” keyword values are stored in memory in the same way as other variables.

04. Accessibility:

  • The “const” keyword values are accessible throughout the program.
  • The “readonly” keyword values are accessible only within the class where they are declared.

05. Performance:

  • The “const” keyword values have better performance as they are stored in memory as part of the assembly or program metadata.
  • The “readonly” keyword values have slightly lower performance as they are stored in memory like other variables.

When to use constant?

  • When you need to declare a constant value that will not change during the execution of the program.
  • When you need to access the constant value from multiple classes without creating an instance of the class.
  • You can use the constant when performance is a concern.

When to use readonly?

  • When you need to declare values to be initialized only once, either at the declaration or in a constructor.
  •  When you need to restrict the accessibility of the value to only within the class where it is declared.
  •  When you need to change the value at runtime based on some conditions.

Comparison of readonly and const keywords in C#

Keyreadonly keywordconst keyword
Keyword:In C#, readonly fields can be created using the readonly keyword.Constant fields are created using the const keyword.
Type:readonly is a runtime constant.At the same time, const is a compile-time constant.
Access:We can access readonly variables by using an instance of a class.You can use a ClassName.ConstantName notation to access them.
Change Value:The value of a readonly variable can only be altered using the constructor during runtime, but not through a member function.On the other hand, constants are automatically static, and We cannot modify their value from any source, including the constructor, function, or runtime.
Declaration:Fields marked as readonly cannot be declared within a method.However, fields that are labeled as const can be declared within a method.
Value:The readonly value can vary with each instance.at the same time, the value of a constant is the same across all objects and must be initialized with a literal expression.
ReadOnly vs Const in C#

When to use const and readonly in C#

The choice between const and readonly depends on the specific use case. If you have a value that will never change, then you should use const. If you have a value that may change during runtime but only during initialization or in the constructor, then you should use readonly.

For example, if you have a mathematical constant such as π (pi), you should declare it as const:

const double pi = 3.14159265358979;

On the other hand, if you have a value that needs to be initialized from a database or user input, you should declare it read-only:

class Person
{
    public readonly int userAge;
    public Person(int age)
    {
        userAge = age;
    }
}

FAQs

Below is a list of frequently asked questions about the difference between readonly and const keywords in C#

Q: What is the purpose of using the readonly keyword in C#?

The readonly keyword is used to create a readonly field in C#, meaning we cannot change its value after it is declared. However, we can only set it during declaration or runtime in the constructor.

Q: What is the purpose of using the const keyword in C#?

The const keyword creates a constant field in C#, meaning its value must be assigned at compile time and cannot change afterward.

Q: Can a readonly field be declared within a method in C#?

No, a read-only field cannot be declared within a method. It must be declared as an instance variable and assigned a value when declared or in a constructor of the same class.

Q: Can a const field be declared within a method in C#?

Yes, a const field can be declared inside a method in C#, but we must assign its value during declaration time.

References: MSDN-ReadOnly in C#, geeks for geeks- readonly and const keyword in C#

Articles you might also like:

Let others know about this post by sharing it and leaving your thoughts in the comments section.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments