Explain the difference between const and readonly keywords in C#

CsharpServer Side ProgrammingProgramming

In C#, both the const and readonly keywords are used to define immutable values which cannot be modified once they are declared. However, there are some important differences between the two.

const

The const modifier declares the constant values that are known at compile-time and do not change, i.e. they are immutable. In C#, you can mark only the built-in types as const. User-defined types such as classes, structs, etc. cannot be const. Also, class member types such as methods, properties, or events cannot be marked as constants.

You must initialize the constants during declaration.

class Period{
   public const int hours = 12;
   public const int minutes = 60;
}

Constants can be marked with any visibility modifier, i.e. private, public, protected, protected internal, or private protected.

Constants also act as static values, i.e. the value of the constant is the same for all instances of the class. You don't have to mark them explicitly with the static keyword. You can't access the constants using the instance variables of that class but have to use the class name.

readonly

A field marked as readonly can only be assigned during the declaration or in the constructor. Once the instance of the class is created, you can't modify a readonly field.

If the field is a value type, marking it readonly makes it immutable. On the other hand, if a readonly field is a reference type, then you can still change the data of the object referenced by the variable. However, you can't change that reference to point to a new object.

class Person{
   private readonly string _title;
   private readonly string _skill;
   public Person(string title, string skill){
      _title = title;
      _skill = skill;
   }
}

A readonly field can be assigned multiple times in the field declaration and in any constructor. Also, it can have different values depending on the constructor used.

An important difference between the two is when a const or readonly field declared in one assembly is compiled when used in another assembly.

  • In the case of the const value, it is like a find-replace. The constant value is 'baked into' the second assembly's intermediate language. This means that if you update the constant, the second assembly would still have the first value until you recompile it.

  • In the case of the readonly value, it is like a reference to a memory location. The value is not baked into the second assembly's intermediate language. This means that if the memory location is updated, the second assembly gets the new value without recompilation. Updating the readonly field means only the first assembly needs to be compiled without any user assemblies having to compile.

Example

 Live Demo

using System;
class Program{
   static void Main(){
      Console.WriteLine(Period.HOURS);
      var person = new Person("John", "Programmer");
      person.Print();
   }
}
class Period{
   public const int HOURS = 12;
   public const int MINUTES = 60;
}
class Person{
   private readonly string _title;
   private readonly string _skill;
   public Person(string title, string skill){
      _title = title;
      _skill = skill;
   }
   public void Change(string skill){
      // Error: A readonly field cannot be assigned to
      // this._skill = skill;
   }
   public void Print(){
      Console.WriteLine($"{_title}: {_skill}");
   }
}

Output

12
John: Programmer
raja
Published on 19-May-2021 07:50:10
Advertisements