Friday 25 November 2016

Practical difference between constant and readonly in c#?


      
              Constant(const)


                    Readonly

Constant is immutable values and do not change their value for the life of program.
Constants are known as compile time.


ReadOnly is also immutable value and do not change their value for the life of program.
ReadOnly is known as runtime.
Assigned a value at the time of declaration.
Ex:-
public const int number = 0;

Assigned a value  either at run time or inside a constructor(instance initialization).

Ex:-
class Program
    {
        public readonly int number = 10;
        public Program()
        {
            number = 20;
        }
    }



Constant cannot be static i.e you cannot declared constant as static.

Ex:-
public static const int number = 10;

It will throw error at compile time.

Readonly can be static i.e you can declare readonly as static.

Ex:-
public static readonly int number = 10;

It will not give an error.
Constant value can access with class name.

Ex:-
class Program
    {
        public  const int number = 10;
       
        static void Main()
        {
            Console.Write(Program.number);
        }

    }



Readonly value can access by instance of class.

Ex:-
class Program
    {
        public  readonly int number = 10;
        
        static void Main()
        {
            Program p=new Program();
            Console.Write(p.number);
        }
    }