C# Difference between Constant and ReadOnly with Examples

  By : Suresh Dasari
  Posted On : 02-May-2023

Here, we will learn what is constant in c#, what is readonly in c#, how to use constant and readonly in c#, and the differences between constant and readonly in c# with examples.

What is Constant in C#?

In c#, the const keyword is useful to define the constant variables. In c#, while defining the constant variables those must be initialized during the declared. Once the value is assigned to the constant variable that value will not change throughout the applications.

 

Following is the example of declaring and initializing the constant variables in c# using the const keyword.

 

const int age = 35;
const string name = "Suresh";

The constant field values will be evaluated at compile-time, and they cannot be changed once it is assigned.

 

To learn more about the constant in c#, visit Constant in C# with Examples.

What is ReadOnly in C#?

In c#, the readonly keyword is useful to define the readonly variables. The readonly fields can be initialized at the time of declaration or in the constructor of the class.

 

Following is the example of declaring and initializing the readonly fields in c# using readonly keyword.

 

class User
{
   // Initialize ReadOnly Fields
   public readonly string name = "Suresh";
   public readonly string location;
   public readonly int age;
   public User()
   {
      location = "Hyderabad";
      age = 32;
   }
}

The readonly field values will be evaluated at runtime. Once the values are assigned to the readonly fields those will be same throughout the application.

 

To learn more about readonly in c#, visit ReadOnly in C# with Examples.

Differences between Constant and ReadOnly in C#

As discussed, const and readonly keywords are useful to define the constants. The following table lists the differences between constant and readonly in c#.

 

ConstantReadOnly
By using the const keyword, we can create constant fields in c#. The readonly keyword is useful to create the readonly fields in c#.
The constant fields must be initialized during the declaration. The readonly fields can be initialized during the declaration or in the constructor of the class.
Once the value is assigned to the constant variable that will not change throughout the application. The readonly field values can be modified at the constructor or at runtime.
The constant fields are evaluated at compile time. The readonly fields are evaluated at run time.

To learn more about const, readonly keywords, and other topics in c#, visit C# Tutorial