博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Practical Difference between Const & ReadOnly
阅读量:2348 次
发布时间:2019-05-10

本文共 4487 字,大约阅读时间需要 14 分钟。

原帖地址:

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.

转载地址:http://zaovb.baihongyu.com/

你可能感兴趣的文章
在Fragment中OnActivityResult方法中接收Activity中返回的值
查看>>
外包采用Gradle生成多套app打包
查看>>
iOS和Android的app界面设计规范
查看>>
Android 代码混淆异常
查看>>
Android drawable微技巧,你所不知道的drawable的那些细节
查看>>
理解Fragment生命周期
查看>>
最靠谱的禁止ViewPager滑动方法
查看>>
android错误之android.content.res.Resources$NotFoundException:
查看>>
Android监听软键盘打开收起事件(软键盘自带收起按钮)
查看>>
huffman code and encode
查看>>
exception in c++
查看>>
java并发编程lock
查看>>
阿里云技术教程系列-ECS远程连接 Linux 实例
查看>>
Linux新建用户并允许docker
查看>>
Drools Workbench 7.5.0.Final安装运行
查看>>
Docker快速部署Redis
查看>>
Spring boot shiro session cache ecache redis 共存配置
查看>>
一看就懂的设计模式--设计模式分类
查看>>
一看就懂的设计模式--模板方法
查看>>
一看就懂的设计模式--享元模式
查看>>