Saturday, 24 December 2016

Difference between Static variable and Static read only variable in C#

In this post we are going to see what is the difference between Static Variable and Static read only variable in C#, For this to check we are taking a sample class which can be very useful to discuss.

we need a static variable to assign a static instance value. Static variable will be used to assign value in all places, but for static read only we will able to assign value only in constructor. Let we see two classes one with static variable another one with static read only



Static : Static constructor, Normal constructor, properties etc






Static Read Only : It will allow the assignment in Static constructor, But in other places we can see the Error if user assign the value.









Static :
**********************
In Static variable we can assign the value in static constructor, normal constructor, inside properties etc



    public class PlanetarySystem
    {
        private static PlanetarySystem _instance;

        static PlanetarySystem()
        {
            _instance = new PlanetarySystem();
        }

        public PlanetarySystem(){           
        }

        public static PlanetarySystem Instance
        {
            get
            {
                _instance = new PlanetarySystem();
                return _instance;
            }
        }

        public string PlanetName { set; get; }

        public int Rotation { set; get; }

        public void Rotate()
        {
            Console.WriteLine("Rotating ... ");
        }
      

    }




Static Read only:
*********************
In static readonly we can assign the value only inside of the static constructor, other ways are not allowed.

    public class PlanetarySystem
    {
        private static readonly PlanetarySystem _instance;

        static PlanetarySystem()
        {
            _instance = new PlanetarySystem();
        }

        public PlanetarySystem(){                   
        }

        public static PlanetarySystem Instance
        {
            get
            {             
                return _instance;
            }
        }

        public string PlanetName { set; get; }

        public int Rotation { set; get; }

        public void Rotate()
        {
            Console.WriteLine("Rotating ... ");
        }
      
    }




From this post you can see what is the difference between static and static read only variable