Difference Between Constant,Readonly and Static in C#.

Difference Between Constant,Readonly and Static in C#

Constant:


        When want we declare a fixed value then we assign a value at the time of declaration.At the compile time we decide the value of variable of constant.i.e
Public Const PI=3.14

Valid Declaration of Constant

public const int a=20;
public const int b=a+10;


In Valid Declaration of Constant

public const int a=x;
public const int b=a+x;
public const double DISCOUNT = (price /100 ) * 3;


Feature
Value are evaluated at compile time.
Constant value can not calculate by variable.

Real Scenrio where we use Constant
To Store the employee name
Store Company Name


ReadOnly:

The Read only variable is just like constant but it can be changed at run time .It's value can be changed according to requirement when constructor of class called.

i.e

Class XYZ
{
      public readonly int a=10;
     public xyz(){
      a=20;
      }
}

Real Scenrio where we use Readonly
When you want to get list of Employee then you can assigned list variable at time of Constructor called.

Readonly can not changed the value when the constructor is called.



Static:

There are two type of Fields in a Class  First is Static and Second is instance in C#.
the staic filed is not a part of instance of class .No matter how many instance of class is created.there is only one copy of static fileds.


We can Easily understand by following program.

class XYX
    {
        
        readonly int read = 10;
        const int cons = 10;
        public static  int _a = 6;
        public XYX()
        {
            read = read+100;
            _a = _a + 10;
         //   cons = cons + 10; this is not a valid statement
           
        }
        public void test()
        {
            Console.WriteLine("Read only : {0}", read);
            Console.WriteLine("const : {0}", cons);
            Console.WriteLine("Static: {0}", _a);
        }
    }


 class Program
    {
        static void Main(string[] args)
        {
            XYX _obj = new XYX();
            _obj.test();
            XYX _obj1 = new XYX();

            _obj1.test();
            XYX _obj2 = new XYX();
            _obj2.test();

            Console.ReadLine();
        }
    }

Explanation
    the output of the above program is
In First instance of class called

Read only:110
const:10
Static:16

In Second instance of class called

Read only:110
const:10
Static:26

In Third instance of class called

Read only:110
const:10
Static:36

Constant value is always constant and in each instance it will be same.
Readonly value will change at run time and in each instance it readonly variable can't hold previus value
Static:the static variable hold last value in each instance .

Comments

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A