A programmatic close look at constant and read-only variables in C#

Esensahoo
Posted by in C# category on for Intermediate level | Points: 250 | Views : 13197 red flag
Rating: 5 out of 5  
 1 vote(s)

Many time we get question in interview that what is the difference between constant and readonly.I have listed out most of the difference and to make it more clear I have also given sample code/steps to test every point in this comparison. I hope this will be useful.

Introduction


This article explains the difference between constant and read-only variables using simple programs.  


                       Constant

                           Read-only

This is like static variables and can not be accessed through object.

Example:

class Program

    {

       static void Main()

        {

            X o = new X();

            int k = o.i;//Error

            int k = X.i; //No Error

        }

    }

    class X

    {

        public const int i=10;

    }

Can be accessed through objects like a normal instance variables.

Example:

class Program

    {

       static void Main(string[] args)

        {

            X o = new X();

            int k = o.i;//No Error

            int j = X.i;//Error

        }

    }

    class X

    {

        public readonly int i=10;

    }

Can't be declared static (when declared in a class by default it is a class level variable )

 

Example:

class X

    {

        public static const int i=10;//Error

    }

Can be declared static.

 

Example:

class X

    {

       public static readonly int i=10; //No Error

    }

Value is evaluated at compile time.

Example :

static int k = 10;//assigned at runtime

const int i=k;//Error since k value is assigned at runtime.

Value is evaluated at runtime like a normal variable

Example :

static int k = 10;//assigned at runtime

readonly int i=k; //No error

Initialized at declaration only.

Example:

   (1)public const int i = 25; //No Error

   (2)public const int i ;//Error

                     i=25;//Error

   (3)

class X

    {

        const int i;//Error

        public X()

        {

            i=10;

        }

    }

   (4)

class X

    {

        const int i;//Error

        public void f()

        {

            i=10;

        }

    }

 

Can be initialized at declaration or by code in the constructor.

Example:

   (1)public readonly int i = 25; //No Error

   (2)public readonly int i ;//Error

                     i=25;//Error

   (3)

class X

    {

        readonly int i;//No Error

        public X()

        {

            i=10;

        }    

    }

   (4)

class X

    {

        readonly int i;//Error

        public void f()

        {

            i=10;

        }

    }

 

Can be declared and initialized in a method.

Example:

class X

    {

        public void f()

        {

            const int i = 10;//No Error

        }

    }

Can not be declared and initialized in a method.

Example:

class X

    {

        public void f()

        {

            readonly int i = 10;//Error

        }

    }

Referring assembly preserves the value at compile time.


Example:


Follow the below steps to understand this :


1. Create an assembly MYTEST.dll using below code

namespace MYTEST

{

    public class X

    {

        public const int i = 10;

    }

}


2. Create a Console application(say Constant) and add reference to MYTEST.dll and write below code to print the value of the constant i and compile the program to create Constant.exe assembly.

namespace Constant

{

    class Program

    {

       static void Main()

        {

            Console.WriteLine(MYTEST.X.i);

            Console.Read();

        }

    }

}


3. Now open the bin/Debug directory of constant application and run/doubleclick on Constant.Exe. Output will be 10.


4.Change the value of the constant in MYTEST program as below and recompile it to MYTEST.dll

namespace MYTEST

{

    public class X

    {

        public const int i = 20;

    }

}

5. Open the bin/Debug directory of constant application and replace MYTEST.dll with the new dll.


6. Run/doubleclick on Constant.Exe. Output will be still 10.

 

Value changes in referring assembly if modified in the source assembly.


Example:


Follow the below steps to understand this :


1. Create an assembly MYTEST.dll using below code

namespace MYTEST

{

    public class X

    {

        public readonly int i = 10;

    }

}


2. Create a Console application(say Readonly) and add reference to MYTEST.dll and write below code to print the value of the readonly variable i and compile the program to create Readonly.exe assembly.

namespace Readonly

{

    class Program

    {

       static void Main()

        {

            Console.WriteLine(MYTEST.X.i);

            Console.Read();

        }

    }

}

3. Now open the bin/Debug directory of Readonly application and run/doubleclick on Readonly.Exe. Output will be 10.


4.Change the value of the Readonly variable in MYTEST program as below and recompile it to MYTEST.dll

namespace MYTEST

{

    public class X

    {

        public readonly int i = 20;

    }

}

5. Open the bin/Debug directory of Readonly application and replace MYTEST.dll with the new dll.


6. Run/doubleclick on Readonly.Exe. Output will be still 20.

 



Conclusion

I hope this will help to get a clear understanding on const and read only keyword.

Page copy protected against web site content infringement by Copyscape

About the Author

Esensahoo
Full Name: SATYA SAHOO
Member Level: Starter
Member Status: Member
Member Since: 12/28/2010 8:47:18 AM
Country: India


Working in Misys Software solution having interest in learning and writing on MS.Net technologies.

Login to vote for this post.

Comments or Responses

Posted by: Rtpharry on: 1/5/2011 | Points: 25
Is this article technically correct? I don't know all the technical details about the differences but it seems that the readonly examples are wrong in several places.

"Can be declared static."
class X

{
public static int i=10; //No Error
}


this is just a normal static int, shouldnt it be:
class X

{
public static readonly int i=10; //No Error
}


The next box uses
const int i=k; //No error

which I would expect to be
readonly int i=k; //No error


And then the "Can be initialized in declaration or by code in the constructor." box uses both readonly and const in a single declaration.
Posted by: Esensahoo on: 1/5/2011 | Points: 25
Thanks harry for pointing it ....while copying pate from my visual studio I have done some mistake.I will correct it and post it again.
Posted by: Esensahoo on: 1/5/2011 | Points: 25
Harry, I have updated the post.There were some places where I had missed readonly keyword and some places I had used constant key word in read-only column.It was a mistake during copy paste .I apologizes all the readers for this mistake. Please feel free to comment if you find any mistake in the post.Many thanks to Harry once again.

Login to post response

Comment using Facebook(Author doesn't get notification)