Home » Difference between read-only and const keyword in C#

Difference between read-only and const keyword in C#

Const and Read-only

Const:

In this article, we are going to discuss the two keywords in c#. const keyword used to declare the constant variable in the program. The constant variable is constant throughout the program, once we assign value to the constant variable we can’t change it.

Example:

    class GeekFrisk
    {
        public const int a = 10;
        public const string WebsiteName = "geekfrisk";
        static void Main(string[] args)
        {
            Console.WriteLine("Value of a {0}",a);
            Console.WriteLine("Value of Website {0}", WebsiteName);
            Console.ReadLine();
        }
    }

Read-Only:

In c#, we can use the Readonly keyword to declare the read-only variable. we can assign the read-only value when we declare or in the constructor, we can assign value to the variable.

Example:

class GeekFrisk
{

    public readonly int Age = 25; //Assign value when we declare the variable
    readonly int A;
    readonly string Website;
    public GeekFrisk(int b, string WebsiteName)
    {
        A = b;
        Website = WebsiteName;
        Console.WriteLine("Age {0}", Age);
        Console.WriteLine("Value of A = {0} "+" and "+ "Value of Website = {1} ",A,Website);
    }
    static void Main(string[] args)
    {
        GeekFrisk geekFrisk = new GeekFrisk(10, "geekfrisk");
        Console.ReadLine();
    }
}

Difference between ReadOnly and Const Keyword:

ReadOnly KeywordConst Keyword
Readonly field created using readonly keywordThe constant field created by using the const keyword
Assign read-only field while declaration or in the constructorConstant field assign only when declaring the field
We can’t create/declare a read-only field inside the functionWe can create a const field inside the function
Readonly is Runtime constant. Const is compile-time constant.
Value of Readonly field can be changeValue of Const field can’t be changed
Static modified we can use with readonlyStatic modified we can’t use with const

Need help?

Read this post again, if you have any confusion or else add your questions in Community