C#: Constants and Read-Only

 

Constants in C#:

Constants variables are variables whose values are known at compile-time and these variable values won't change. We can create constants as shown below.

 

                                             const int iId = 10;

 

If you are trying to change the iId value, it gives compile-time error. Constant variables are static internally, so we can access constant variables through class name without creating the object.

 

Read-Only in C#:

We can initialize the read-only variables while declaration as well as in constructors. Other than in constructors if you try to change the read-only variables value it produces compile-time error.  We can create read-only variables as shown below.

 

class Employee

{

        readonly int iId;

 

        private Employee()

        {

            iId = 10;

        }

}

 

Read-only variables are not static internally, so we have to use static keyword to access readonly variables through class name as shown below.

          

                             readonly static int iId = 10;