const and readonly keyword in C#
There is two way to declare constant variables one is by using const keyword and other is by using readonly keyword. The main difference between these two is, the first one is used to create a constant variable at compile time while the other one is used to create a constant variable at run time. Below is a detailed explanation of these two keywords:
Const
the const keyword is used to create the constant variable. Its value is given at compile time meaning that its value is given at the same time when we declare it. Its value will be the same during the lifetime of the program meaning that its value does not change once given. Static keyword can not be used with these type of variables because by default they are static.
Example:
using System;
class Test {
// Constant variabless
public const int var1 = 100;
public const string str1 = "Rahul";
static public void Main()
{
Console.WriteLine("The value of var1: {0}", var1);
Console.WriteLine("The value of str1: {0}", str1);
}
}
Output:
The value of var1: 100
The value of str1: Rahul
ReadOnly:
readonly keyword is used to create the read-only variable. Its value is given at run time meaning that its value is given at the same time when we declare it or under the class constructor. Static keyword can be used with these type of variables because by default they are non-static.
Example
using System;
class Test{
// readonly variables
public readonly int var1;
public readonly int var2;
public Test(int v1, int v2)
{
var1 = v1;
var2 = v2;
Console.WriteLine("The value of var1: {0}", var1);
Console.WriteLine("The value of var2: {0}", var2);
}
// Main method
static public void Main()
{
Test obj = new Test(100, 200);
}
}
Output
The value of var1: 100
The value of var2: 200
Below are some differences between const and readonly keyword in C#:
const | readonly |
They are created using the const keyword. | They are created using the readonly keyword. |
It is a type of constant whose value is given at compile time. | It is a type of constant whose value is given at the run time. |
After declaration, it is not possible to change the value. | After declaration, it is possible to change the value. |
It is possible to declare a constant variable within a method. | It is not possible to declare a read-only variable within a method. |
Static keyword can not be used with these type of variables because by default they are static. | Static keyword can be used with these type of variables because by default they are non-static. |