Practical Difference between Const & ReadOnly

原帖地址:http://www.codeproject.com/Tips/803656/Practical-Difference-between-Const-ReadOnly

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).

    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

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.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值