Search This Blog

Saturday 19 December 2015

Const Vs Readonly Vs Static in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConstVsReadonlyVsStatic
{
    class Program
    {
        public const double PI = 3.14159;
        public readonly string strReadonlyHello = "Readonly Hello";
        public static string strStaticHello = "Static Hello";

        public Program() // Constructor
        {
            strReadonlyHello = "Constructor Readonly Hello";
        }

        public void Display()
        {
            //Error: The left-hand side of an assignment must be a variable, property or indexer
            //PI = 3.125;

            //Error: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
            //strReadonlyHello = "Hello";

            Console.WriteLine("Readonly value change in Constructor - {0}", strReadonlyHello);

            Console.WriteLine("Static value before change - {0}"Program.strStaticHello);

            Console.WriteLine("Enter the value to change the static variable value");
            strStaticHello = Convert.ToString(Console.ReadLine());

            Console.WriteLine("Static value after change - {0}"Program.strStaticHello);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Display();

            Console.ReadLine();
        }
    }
}

Output:


 

Conclusion:
        
Constant (const):

1. A const field requires a value to be provided at compile-time.
2. Const field value cannot be change once assigned.

         
Readonly:

1. A readonly field cannot be assigned to (except in a constructor or a variable initializer)
        
Static:

1. A static variable is a variable that has been allocated statically—whose lifetime
   or"extent" extends across the entire run of the program.
        
         
For More info about variable initializer refer below link
        


No comments:

Post a Comment