Difference Between Constant and Read-only in C# with example

Difference Between Constant and Read-only in C# with example

Constant

Constant variables are declared and initialized at compile time. The value of the Constant can’t be changed.

const keyword can be applied to value type and reference type which can be assigned with a value null.

Example

static void Main(string[] args)

   {

       const int a = 10;

       const int b = 20;

 

       const int c = a + b; // no error as both a and b are const variable

 

int z = 20;

const int d = a + z; // error message "The expression being assigned to d must be const" on runtime as both a and z are not Const variable.

            

Console.WriteLine("Result of a+b = "+c);

       Console.ReadKey();

   }

To declare reference type as a Constant it has to assign with Null value.

Const Class1 obj1 = null; //no error

const Class2 obj2 = new Class2(); //error on run time

 

Read-Only

Read –Only variables are declared and initialized on run time. The value of the Read-only variable can be changed in the constructor of the class.

readonly keyword can be apply to value type and reference type which initialized by using the new keyword. Delegate and event cannot be read-only. Read-Only Variable can be declared as static.

Example

class Program

{

        readonly int x = 10;

        public Program()

        {

            x = 20;// changed the value in the constructor

        }

}


Difference between Constant and Read-only

Constant

Read-Only

Value never changed.

Value can be changed in the constructor of the class.

Declared and Initialized in Compile time.

Declared and Initialized in Run time.

By default Constant is static, Cannot be declared as static.

Can be declared as Static.

 

Summary

I hope this article help you to understand the difference between Constant and Read-only and when to choose what. Please share your valuable feedback on this.

comments powered by Disqus

Related Articles