Just4Fun - Comparaison between const and readonly in C#
/* By Dylan SUN */
Today let us talk about const and readonly.
- const is considered as compile-time constant
- readonly is considered as runtime constant.
I will demonstrate some example code to clarify their usages and differences.
I. Const usages
Firstly, you can see that const variable can be declared and assigned at class level.
public class ConstExample
{
public const string CstValue1 = "hello"; //Correct
}
You can also declare a const variable in constructor
public ConstExample()
{
const string cstValue6 = "hehe"; //Correct
}
You can see that const can be declared at method level too
public void Display()
{
const string cstValue2 = "cst 2"; //Correct : Constant can be declared in method
}
If you want to assign another value to CstValue1, you will get an compile-time exception. Because const can only be assigned when declaration.
CstValue1 = "hello2"; //Compile time exception : Can not resolve symbol CstValue1
You can not also assign another value to CstValue1 in the constructor. You will get an compile-time exception.
public ConstExample()
{
CstValue1 = "hello2"; //Compile time exception : Constant can not be used as an assignment target
}
May be you want to assign a normal string variable to a const like this. But you will see it doesn’t work too.
public string v1;
const string CstValue2 = v1; //Compile time exception : Constant initializer must be compile-time constant
But you can assign the operation result of several consts to another const like this.
public const string CstValue3 = "world"; //Correct
public const string CstValue4 = CstValue1 + CstValue3; //Correct : Constants can only be assigned with values or with consts
You can also declare a const, and assign it with the addition of two consts in the method.
const string cstValue5 = CstValue1 + CstValue3;
When you display them you can see
Console.WriteLine(CstValue1); //=> hello
Console.WriteLine(cstValue2); //=> cst 2
Console.WriteLine(CstValue4); //=> helloworld
Console.WriteLine(cstValue5); //=> helloworld
II. readonly usages
Firstly, you can declare an readonly variable at class level.
public class ReadOnlyExample
{
public readonly string rdValue1 = "good";
}
You can also just declare a readonly variable without assigning any value to it.
public readonly string rdValue2;
You can not declare a readonly variable in a method.
readonly string rdValue6 = "hohoho"; //compile time exception : statement expected
You cannot assign a value to variable rdValue1 after the declaration, except for, you assign a value in the class constructor.
rdValue1 = "good 2"; //Compile time exception : Can not resolve symbol rdValue1
You can not assign a readonly variable to another readonly variable at class level.
readonly string rdValue3 = rdValue1; //Compile time exception : cannot access non-static field 'rdValue1' in static context
You can not assign a normal variable to a readonly variable neither at class level.
public string value1 = "hey";
readonly string rdValue6 = value1; //Compile time exception : cannot access non-static field 'value1' in static context
You can not assign value to a readonly variable in a method.
public void Display()
{
rdValue1 = "good one"; //Compile time exception: Readonly field can not be used as an assignment target
rdValue2 = "good too"; //Compile time exception: Readonly field can not be used as an assignment target
}
But you can assign a normal variable to a readonly variable in class constructor.
You can even assign the operation result of several readonly variables to another readonly variable.
public readonly string rdValue4;
public readonly string rdValue5;
public ReadOnlyExample(string value)
{
rdValue2 = value; //Correct
rdValue4 = rdValue1 + rdValue2; //Correct : Assign another readonly variable to another readonly variable can only be done in constructor
rdValue5 = rdValue1 + value1; //Correct : Assign readonly variable with normal variable to another readonly variable
}
when you display them, you will see
Console.WriteLine(rdValue1); //=> good
Console.WriteLine(rdValue2); //=> day
Console.WriteLine(rdValue4); //=> goodday
Console.WriteLine(rdValue5); //=> goodhey
If you want to access to a const, you must access it via the class
Console.WriteLine(ConstExample.CstValue1); //Const variable can only be accessed by class
If you want to access to a readonly variable, you must access it via an instance of class.
var re = new ReadOnlyExample("day");
Console.WriteLine(re.rdValue1); //Readonly value can only be accessed by instance of class
So to conclude,
Const :
Can only be assigned at declaration
Can be declared at class level, in constructor and in method.
Can be assigned with operation result of several consts at class
level or in constructor or in method. (like addition, multiplication
etc)Once the declaration is done, you can never modify a const’s value, neither in constructor, nor just after declaration.
You can access const variable only by class.
Readonly:
Can only be assigned at declaration or in constructor.
Can be declared only at class level. You can declare a readonly
variable neither in constructor nor in method.Can be assigned with operation result of several readonly variables only in constructor (like addition, multiplication etc). You can not assign them to a readonly variable when declaration or in a method.
You can access Readonlyvariable only by the instance of class.
I hope you find this article helpful!
版权声明:本文博主原创文章,博客,未经同意不得转载。
Just4Fun - Comparaison between const and readonly in C#的更多相关文章
- C#基础知识七之const和readonly关键字
前言 不知道大家对const和readonly关键字两者的区别了解多少,如果你也不是很清楚的话,那就一起来探讨吧!探讨之前我们先来了解静态常量和动态常量. 静态常量 所谓静态常量就是在编译期间会对变量 ...
- const 与 readonly知多少
原文地址: http://www.cnblogs.com/royenhome/archive/2010/05/22/1741592.html 尽管你写了很多年的C#的代码,但是可能当别人问到你cons ...
- [c#基础]关于const和readonly常见的笔试题剖析
引言 有那么几天没更新博客了,发现到了不得不写的地步,总是有那么个声音在强迫自己,虽然工作很累,但是有些东西不写出来,不能原谅自己.今天为什么总结这两个关键字的区别,总觉得这两个关键字的用法用的太习惯 ...
- const 和 readonly
const 和 readonly 的异同 Const readonly 字面意 不变常量,不可修改 只读操作,不可写 初始化 必须在声明的同时赋值 可在声明和构造方法中进行赋值 所属关系 类.即sta ...
- C#夯实基础系列之const与readonly
一.const与readonly的争议 你一定写过const,也一定用过readonly,但说起两者的区别,并说出何时用const,何时用readonly,你是否能清晰有条理地说出个一二三 ...
- 读书笔记:const和readonly、static readonly 那些事
C#中表示不变的量(常量)的两种形式:const 和readonly const 是静态常量 readonly 是动态常量 严格的来讲:const 应该称为常量 而readonly 则应称为只读变量. ...
- const和readonly区别
内容来源<<你必须知道的.NET>>(转载) 标题:什么才是不变:const和readonly 内容: const:用 const 修饰符声明的成员叫常量,是在编译期初始化并嵌 ...
- [转]const 与 readonly知多少
引自:http://www.cnblogs.com/royenhome/archive/2010/05/22/1741592.html 尽管你写了很多年的C#的代码,但是可能当别人问到你const与r ...
- const与readonly深度分析(.NET)
前言 很多.NET的初学者对const和readonly的使用很模糊,本文就const和readonly做一下深度分析,包括: 1. const数据类型的优势 2. const数据类型的劣势 3. r ...
随机推荐
- Swift - 各种手势检测大全(UIGestureRecognizer及其子类)
UIGestureRecognizer有许多子类,用于监听一些常见的手势事件,这些子类主要有: 1,UISwipeGestureRecognizer:滑动(快速移动) 1 2 3 4 5 6 7 8 ...
- html5实现拖拽文件上传
以下是自学it网--中级班上课笔记 网址:www.zixue.it html文件 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict ...
- 【前段开发】10步掌握CSS定位: position static relative absolute float
希望能帮到须要的人,转自:http://www.see-design.com.tw/i/css_position.html 1. position:static 元素的 position 屬性默認值為 ...
- 使用VS插件在VS2012/2013上编辑和调试Quick-Cocos2d-x的Lua代码
vs 也能够做lua 开发,并进行代码调试 依照以下文档,调试没问题. 參考文档: 点击打开链接
- OpenCV HaarTraining代码解析(二)cvCreateMTStumpClassifier(建立决策树)
HaarTraining关键的部分是建立基分类器classifier,OpenCV中所採用的是CART(决策树的一种):通过调用cvCreateMTStumpClassifier来完毕. 这里我讨论利 ...
- 日交易41.9亿,B2B的魅力为何不输于B2C、C2C?
在最近两年的电子商务版图中,B2C和C2C可谓大放异彩,相比之下,B2B却显得颇为“低调”,当然,低调并不代表没有影响力,只不过,相比B2C和C2C面向数亿网民而言,B2B只针对企业和商家服务 ...
- Java Web----Java Web的数据库操作(二)
Java Web的数据库操作 三.JDBC操作数据库 上一篇介绍了JDBC API,之后就可以通过API来操作数据库,实现对数据库的CRUD操作了. http://blog.csdn.net/zhai ...
- Nginx 负载均衡-加权轮询策略剖析
本文介绍的是客户端请求在多个后端服务器之间的均衡,注意与客户端请求在多个nginx进程之间的均衡相区别(Nginx根据每个工作进程的当前压力调整它们获取监听套接口的几率,那些当前比较空闲的工作进程有更 ...
- Filezilla出现中文乱码
使用Filezilla client FTP客户端登陆某些FTP站点会出现中文乱码,原因是FTP服务器端编码与filezilla client端编码不一致造成的,解决方法如下:文件-站点管理-选中要登 ...
- centos5.5字体为方块问题的解决_深入学习编程_百度空间
centos5.5字体为方块问题的解决_深入学习编程_百度空间 centos5.5字体为方块问题的解决 一.yum -y install fonts-chinese二.yum -y install f ...