Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
readonly keyword
3.
const keyword
4.
Comparison
5.
Frequently Asked Questions
5.1.
What are keywords?
5.2.
What is the readonly keyword?
5.3.
What is the const keyword?
5.4.
Is the static modifier permitted with the const keyword?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference between readonly and const keyword in C#

Author Nagendra
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

C# is pronounced as C sharp. This is built by Microsoft and operates on the.Net framework. It is closely related to the C programming language, as well as other computer languages such as C++ and Java. Its most impressive feature is its reusability. The language is easy to learn and understand. Keywords are the reserved words that have a special meaning for the compiler. These terms cannot be used as identifiers for variables, classes, or anything else.
Constant fields and constant local are declared with the const keyword. The constant field's value remains constant throughout the program; in other words, once the constant field is assigned, its value cannot be modified.This readonly keyword indicates that the variable can only be assigned when it is declared in a variable or the constructor of the same class in which it is declared.

So first, let us discuss more about readonly and const keyword.

Click on the following link to read further: Features of C Language

readonly keyword

readonly is a keyword in C# that may be used to create read-only fields in our applications. Unlike the constant keyword in C#, the read-only field values must be populated either at the declaration in a function or constructor of the same class. When we employ the readonly keyword with fields, the values of those fields will be evaluated at runtime. We must use the readonly keyword during the declaration of fields in our application to define read-only fields. We can use the readonly modifier with numbers, boolean values, strings, or null references. If we use the readonly keyword to specify a read-only field in C#, the value of that field cannot change once the execution of the constructor has finished. Hence we shouldn't use readonly with fields whose value will change at any moment.
The following are the main properties of the readonly keyword:

  • When an instance is created, they are assessed.
  • For readonly fields, you can use the static modifier.
  • With reference types, the readonly modifier can be utilised.
  • The readonly keyword can only be used for instance or static fields; it cannot be used for variables in methods.

Consider the following code snippet:

using System;
   class ReadOnlyTest  
   {    
    //readonly variable are initilized during declaration or in a constructor
    readonly int RollNo = 1284;
    //Valid
    readonly int marks;
    readonly string Name = "Ninja";
    //readonly fields can be initlized in constructor
    public ReadOnlyTest (string name)
    {
        marks = 90;
        Name = name;    
    }
 
    public changeName(string newName)
    {
        Name = "Ninja"; ; // Will result error.
    }
   }
    class ReadOnlyExample
   {  
        public static void Main()
        {  
        ReadOnlyTest obj = new ReadOnlyTest("Ninja");  
        Console.Read();
        }
   }

Explanation:
In the above code snippet, we have tried to reassign and increment the values of readonly variables, which results in errors.

Example:
Consider the following code snippet:

using System.IO;
using System;
 
public class Result {
   public const int marks = 50;
   public readonly int marks_1;
 
   Result(int marks){
    marks_1 = marks;
   }
   public static void Main() {
    Console.WriteLine(marks);
    Result p1 = new Result(61);
    Console.WriteLine(p1.marks_1);
   }
}

Output :

50
61
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

const keyword

The const is a keyword in C# that can be used to declare constant fields in our programs. In general, constant field values in C# are established at build time and will never change. If we declare a constant field using the const keyword in C#, the value of that field will not change throughout the application. Hence we should not use const with fields whose value will change at any moment. We must use the const keyword during the declaration of fields in our application to define constant fields in C#, and we can utilise constants with numbers, boolean values, strings, or null references. We must initialise constant fields with required values during the declaration process; otherwise, our c# application would generate compile-time problems. The static modifier is not permitted in the declaration of constant variables in C#.

The following are the main properties of the const keyword :

  • By default, const is static.
  • They must have a value at the time of compilation.
  • It's possible to declare it within functions.
  • Every assembly that uses them receives a copy of these.

Consider the following code snippet:

using System;  
    class ConstantExp  
    {          
        private const int x = 9;  
        public static void Main()  
        {  
            //const variables are initialised while declaration
            const int RollNo = 12322;  
            //Valid  
            const int Age = 10 + 13;  
            const string Name = "Ninja";  
   
            // Reassigning a const variable is not permitted.  
            RollNo = 1405; //compile time error.  
            Age++; //compile time error.  
            Console.WriteLine(Name);  
   
            Console.Read();  
        }  
    }

Explanation:
In the above code snippet, we have tried to reassign and increment the values of const variables, which results in a compile-time error.

Example:
Consider the following code snippet:

using System;
class Ninja {
    // Constant fields are initilized during declaration
    public const int variable = 10;
    public const string s = "Ninja";
     public static void Main()
    {
        Console.WriteLine("Value of variable: {0}", variable);
        Console.WriteLine("Value of string: {0}", s);
    }
}

Output:

Value of variable: 10
Value of string: Ninja

Comparison

Learn more, Difference Between Structure and Union

Frequently Asked Questions

What are keywords?

Keywords are the reserved words that have a special meaning for the compiler. These terms cannot be used as identifiers for variables, classes, or anything else.

What is the readonly keyword?

readonly is a keyword in C# that may be used to create read-only fields in our applications. Unlike the constant keyword in C#, the read-only field values must be populated either at the declaration in a function or constructor of the same class. 

What is the const keyword?

const is a keyword in C# that can be used to declare constant fields in our programs. Constant field values in C# are established at build time and will never change.

Is the static modifier permitted with the const keyword?

No, the static modifier is not permitted with the const keyword. It is permitted with the readonly keyword.

Also Read About - singleton design pattern in c# 

Conclusion

In this article, we have extensively discussed the difference between readonly and const keywords in C#. The article explains the detailed difference between readonly and const keyword in C# with examples.
We hope that this blog has helped you enhance your knowledge regarding the difference between readonly and const keyword in C# and if you would like to learn more, check out our articles on C#. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.
Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Live masterclass