Readonly and constant members

What is the difference between Readonly and constant members?

 

Both Readonly and const data members have constant value and can't be changed. But the real this 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();

        }

    }

}

Up Next
    Ebook Download
    View all
    Learn
    View all