Difference between readonly and const keyword in C#

CsharpServer Side ProgrammingProgramming

readonly keyword

readonly keyword is used to define a variable which can be assigned once after declaration either during declaration or in constructor. const keyword is used to define a constant to be used in the program. Following is the valid usage of a readonly and const keywords in C#.

Example

 Live Demo

using System.IO;
using System;

public class Program {
   public const int VALUE = 10;
   public readonly int value1;

   Program(int value){
      value1 = value;
   }
   public static void Main() {
      Console.WriteLine(VALUE);
      Program p1 = new Program(11);
      Console.WriteLine(p1.value1);
   }
}

Output

10
11

Following are some of the important differences between readonly and const keywords.

Sr. No.Keyreadonly keywordconst keyword
1Purposereadonly keyword is used to create a readonly fields.const keyword is used to create constant fields.
2Typereadonly is a constant defined at runtime.const is used to create a constant at compile time.
3Changereadonly field value can be changed after declaration.const field value cannot be changed after declaration.
4Methodreadonly fields cannot be defined within a method.const fields can be declared within a method.
5Value assignmentreadonly variables are declared as instance variable and assigned values in constructor.const fields are to be assigned at the time of declaration.
raja
Published on 15-Apr-2020 10:12:53
Advertisements