What is difference between constant and read-only in C#?

Solution

Constants are the compile time constant i.e. value of a constant field can only be assigned one time and it can not be changed later.

Example: Defining a constant variable

   class Circle
   {
        public const int number = 10;
   }

Read-only members are the runtime constant i.e. value of read-only members can be assigned at runtime inside the constructor of the class.

Example:

   class Circle
    {
        public readonly double PI = 3.14;

        public Circle(bool value)
        {
            if (value)
            {
                PI = 3.142;
            }
        }
    }

In the above example, we are changing the value of read-only field PI inside the constructor of class Circle based on certain condition.

Constants are implicitly static,i.e. we can use a ClassName.ConstantName notation to access constants.

Example:

class Program
{
  static void Main(string[] args)
   {
      Console.WriteLine(Circle.number);
      Console.ReadLine();
     }
}

Output

10

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media