Click here to Skip to main content
15,867,918 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Practical Difference between Const & ReadOnly

Rate me:
Please Sign up or sign in to vote.
4.77/5 (38 votes)
4 Aug 2014CPOL3 min read 130.2K   14   11
This article shows the what's and how's to use const and readonly variables in one's code

Introduction

While programming on C#, it is always suggested that we understand the concepts before we go ahead and implement the code. In this article, let us understand the basic differences between the const and the readonly keywords and also understand how to use them in our code.

This is my first article on code project and would like to contibute and learn more from here.

Background

At a very high level, as per MSDN

Constants are immutable values which are known at compile time and do not change their values for the life of the program. 

Readonly variables are also immutable values which are known at run time and do not change their values for the life of the program.

Hmm..definitions apart, let us understand what this really means to us.

Using the code

Constants:

Constants are declared using a "const" keyword.

Constants should be assigned a value at the time of the variable declaration and hence are known at compile time. Now whenever you declare a constant variable, the C# compiler substitutes its value directly into the Intermediate Language (MSIL).

C++
    class ConstantEx
    {
        public const int number =3;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ConstantEx.number);
            Console.ReadLine();
        }
    }

Now that we understand the value is directly replaced in the MSIL, any modifications you do to the const variable would result in something similar to below

C++
class Program
    {
        static void Main(string[] args)
        {
            // ConstantEx.number = 15   
            // The above line would throw an error as it internally becomes a statement saying 3=15 
            // which is not valid 
            Console.WriteLine(ConstantEx.number);
            Console.ReadLine();
        }
    }

Hence, constants are immutable values which are known at compile time and do not change their values for the life of the program.

 

Readonly :

Readonly variables are a little different from their colleague, const.

Readonly variables are known at runtime, they can be assigned a value either at runtime or at the time of the instance initialization. Again, lets understand through code here.

    class ReadOnlyEx
    {
        public readonly int number = 10;
    }  

    class Program
    {
        static void Main(string[] args)
        {
            ReadOnlyEx readOnlyInstance = new ReadOnlyEx();
            Console.WriteLine(readOnlyInstance.number);
        }
    }

In the above code snippet, the readonly variable is assigned a value at the time of the declaration and is accessed using the instance of the class rather than using the class itself. Now you may have another instance of the class, which might have the readonly number variable assigned to a different value based on some conditions. Can I do it? Yes, because the readonly variables are known at run time.

Let us try doing this.

class ReadOnlyEx
{
    public readonly int number = 10;
    public ReadOnlyEx()
    {
        number =20;
    }
    public ReadOnlyEx(bool IsDifferentInstance)
    {
        number = 100;
    }
}

class Program
{
    static void Main(string[] args)
    {

        ReadOnlyEx readOnlyInstance = new ReadOnlyEx();
        Console.WriteLine(readOnlyInstance.number);

        ReadOnlyEx differentInstance = new ReadOnlyEx(true);
        Console.WriteLine(differentInstance.number);

        Console.ReadLine();
    }
}

You would see different values coming out of the program's output for the two different instance of the class.

Hence,Readonly variables are also immutable values which are known at run time and do not change their values for the life of the program.

 

Now for those "Let me read this interview question" kind of guys:

 

Constants:

1. Constants can be assigned values only at the time of declaration

2. Constant variables have to be accessed using "Classname.VariableName"

3. Constants are known at compile time

Read Only:

1. Read only variables can be assigned values either at runtime or at the time of instance initialization via constructor

2. Read only variables have to be accessed using the "InstanceName.VariableName"

3. Read only variables are known at run time.

 

Now that we understand the differences between them, one can easily determine the appropriate keyword as per the requirement.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer BOA
India India
I work in a software company and I have a never ending appetite for learning and teaching new things. I love kids.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Vipin_Arora5-Jul-16 5:47
Vipin_Arora5-Jul-16 5:47 
Questionthanks that article Pin
zekikaya9-Jan-16 8:17
zekikaya9-Jan-16 8:17 
Suggestionsome other difference is exist Pin
Programmer 18-Oct-14 1:51
Programmer 18-Oct-14 1:51 
Questionconst is compiled into ALL related assemblies Pin
DontSailBackwards5-Aug-14 11:52
DontSailBackwards5-Aug-14 11:52 
SuggestionA Suggestion Pin
Bilal Haider5-Aug-14 0:50
professionalBilal Haider5-Aug-14 0:50 
GeneralMy vote of 5 Pin
Sibeesh Venu5-Aug-14 0:33
professionalSibeesh Venu5-Aug-14 0:33 
Questionminor Pin
tawfik.kh5-Aug-14 0:20
tawfik.kh5-Aug-14 0:20 
QuestionWhat is the difference between 'const' vs 'static readonly'? Pin
iChrisJ4-Aug-14 20:49
iChrisJ4-Aug-14 20:49 
AnswerRe: What is the difference between 'const' vs 'static readonly'? Pin
Vijendra(VJ)4-Aug-14 21:49
professionalVijendra(VJ)4-Aug-14 21:49 
GeneralMy vote 5 Pin
ashumeerut4-Aug-14 5:48
ashumeerut4-Aug-14 5:48 
GeneralRe: My vote 5 Pin
Vijendra(VJ)4-Aug-14 16:42
professionalVijendra(VJ)4-Aug-14 16:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.