Friday 11 May 2018

Difference between constant and read-only in C#


                             Constant and readonly keywords in C# are used to maintain the value throughout the application without any change. But constant should be assigned a value at the time of declaration only, but there is no need to assigned value at the time of declaration of readonly variable, can be assigned a value in constructor. The following example shows below clarifies about the constant and readonly.


using System;

namespace CSHARP_Constant_ReadOnly
{
    class Program
    {
        static void Main(string[] args)
        {
            Abc abc = new Abc();
            abc.Display();
            Console.Read();
        }
    }
    class Abc
    {
        public const int a = 10;
        public readonly int b = 30;
        public readonly int c;
        public Abc()
            {
            b = 80;
            c = 90;
            }
       public void Display()
        {
            //If given values after initialization, then it throws the following errors
           // a = 50;  //The left-hand side of an assignment must be a variable, property or indexer
           // b = 20;   //A readonly field cannot be assigned to (except in a constructor or a variable initializer)
            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.WriteLine(c);
        }
    }
}

Output :-



No comments:

Post a Comment

Note: only a member of this blog may post a comment.