Readonly Vs Const Keywords In C#

In this article, we are going to learn about what is readonly, const keywords, and their difference.

What is Readonly keyword?

A readonly keyword is used to define a variable that can be assigned once after declaration either during declaration or in the constructor.

Example

using System;
 
class Test
 {
    // readonly variables
    public readonly int var1;
    public readonly int var2;
 
    // Using constructor
    public Test(int a, int b)
    {
        var1 = a;
        var2 = b;
        Console.WriteLine("Display value of var1 {0}, "+"and var2 {1}", var1, var2);
    }
 
    // Main method
    static public void Main()
    {
        Test obj1 = new Test(90, 80);
    }
}
Output
Display value of var1 90, and var2 80

What is Const keyword?

Once the variable is defined as const, then the value assigned to that variable cannot be changed throughout the program.

Example

using System;
 
class Test {
 
    // const variables
    public const int var1 = 96;
    public const string var2 = "Riya";
 
    // Main method
    static public void Main()
    {
        Console.WriteLine(var2 + " got " + var1 + " marks in english");
    }
}
Output
Riya got 96 marks in english

Difference between ReadOnly and Const keywords.

 

 ReadOnly Keywords

 Const Keyword

 purpose

ReadOnly keyword is used to create readonly fields.

The const keyword is used to create const fields.

 value can change?

ReadOnly field value can be changed.

Const field value cannot be changed.

Declaration

ReadOnly field cannot be declared within a method.

Const field can be declared within a method.

Assign value

ReadOnly field values can be assigned in the declaration and in the constructor part.

Const fields values can be assigned in the declaration part.

Type

ReadOnly is a runtime constant.

Const is a compile-time constant.

used

It can be used with a static modifier.

It cannot be used with a static modifier.

That’s it.

Also check, Introduction Of OOP Concept In C#

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories