Pradeep
What is the difference between const and static read-only?
By Pradeep in C# on Aug 27 2009
  • Ravindra Chaudhary
    Aug, 2015 4

    constant variable can not be static. and constant variable Value is evaluated at compile time . constant variable can be initialize at the time of declaration.Read Only variable can be initialize at the time declaration and further. read only variable can be static.

    • 0
  • C# Curator
    Aug, 2009 27

    Both Readonly and const data members have constant value and can’t be changed. But the real difference is explained below along with the code.

     

    Readonly Data Members

     

    Readonly are instance data members.

     

    A readonly data member can’t be made property and can be changed in class constructor only.

     

    Const Data Members

     

    Const data members are static and only can be used with class reference and the const data member name.

     

    using System;

     

    namespace readonly_const

    {

        class Program

        {

     

            public class test

            {

     

                public readonly string name = "George";

                public const string coname = "ABC Company LLC";

     

                public test(string name)

                {

                    // you can change the readonly data members only in class constructor

                    this.name = name;

                }

     

    //We can't write a set property for readonly data members

                public string _name

                {

                    get

                    {

                        return name;

                    }

     

                    //set

                    //{

                    //    name = value;

                    //}

                }

            }

     

            static void Main(string[] args)

            {

     

                test obj = new test("Tina Turner");

     

                Console.WriteLine(obj.name);

     

                // You can only change the value of readonly data memebers in class constructor

     

                //obj.name = "Rocky";

     

                Console.WriteLine(test.coname);

                Console.ReadLine();

            }

        }

    }

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS