2
Reply

What is the difference between const and static read-only?

Pradeep

Pradeep

15y
7.2k
0
Reply

    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.

    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();

            }

        }

    }