Please enable Javascript for better experience...
What is the difference between readonly and constant keyword
By Big | Jun 29, 2015 | In Articles | Total Views [ 641 ]
Taged In
(0 Like)
Rate

READONLY and CONST are nearly same but they are different in few places. You can see the differences between these keywords while declaring or assigning access modifiers to them. In this article we will discuss few of these differences between them.

Introduction

While writing code we use readonly and const keywords and get confused while using them. In this article I will try to explain few differences between them.

READONLY and CONSTANT

Let's see the differences between readonly and const keyword.

ConstantReadonly
Constant variables must be assigned a value at the time of declaration (compile-time). You cannot assign value to constant variable anywhere except at the time of declaration. A readonly variable can be initialized either at the time of declaration or within the constructor of same class.
Use const keyword to declare a Constant variable. Use readonly keyword to declare a Readonly variable.
Constant variables are implicitly static. By default readonly it is not static.
A constant field is a compile-time constant. Readonly fields are compile-time as well as run-time constants.
const float pi = 3.14;
readonly string name = 'rahul'; 

or

readonly string _name;
public MyClass(int name)
{
_name = name; // run time initialization
}
You should use constant, if you are confident that the value of the constant will not change. If you think value can change at run time, you can use readonly.
You cannot change constant value due to its static nature. YYou can also make a readonly variable as static which will start acting as constant variable.

 

Hope this article was helpful. Please like, rate this article and please don't forget to comment as your comments are very useful for us and it helps us improving the level of articles. You can also contact us with your queries.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment