2008-09-11 08:02:19 8 Comments
What is the difference between const
and readonly
in C#?
When would you use one over the other?
Related Questions
Sponsored Content
65 Answered Questions
17 Answered Questions
[SOLVED] Difference between decimal, float and double in .NET?
- 2009-03-06 11:31:23
- Tom
- 884120 View
- 2022 Score
- 17 Answer
- Tags: .net floating-point double decimal
10 Answered Questions
[SOLVED] What are the correct version numbers for C#?
- 2008-10-29 17:09:40
- Jon Skeet
- 333944 View
- 2437 Score
- 10 Answer
- Tags: c# .net visual-studio .net-framework-version compiler-version
28 Answered Questions
[SOLVED] What is the best way to iterate over a dictionary?
- 2008-09-26 18:20:06
- Jake Stewart
- 1491145 View
- 2471 Score
- 28 Answer
- Tags: c# dictionary loops
16 Answered Questions
15 Answered Questions
[SOLVED] In C#, what is the difference between public, private, protected, and having no access modifier?
- 2009-03-05 13:48:38
- MrM
- 654670 View
- 706 Score
- 15 Answer
- Tags: c# .net asp.net access-modifiers
17 Answered Questions
11 Answered Questions
31 Answered Questions
[SOLVED] What is the difference between a field and a property?
- 2008-11-17 08:41:38
- Anonymous
- 418894 View
- 1039 Score
- 31 Answer
- Tags: c# properties field
30 comments
@Ryan Efendy 2019-06-04 20:09:07
when to use
const
orreadonly
const
readonly
App.config
, but once it initializes it can't be changed@Bigeyes 2019-04-29 20:26:40
Const: Absolute constant value during the application life time.
Readonly: It can be changed in running time.
@Salman Farsi 2019-01-17 16:27:57
In simple words Const is compile time and readonly is run time.
@Muhammad VP 2018-09-08 06:39:10
CONST
ReadOnly
@Sujit 2012-09-17 11:48:03
A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the
const
keyword and must be initialized as they are declared.A
readonly
member is like a constant in that it represents an unchanging value. The difference is that areadonly
member can be initialized at runtime, in a constructor, as well being able to be initialized as they are declared.const
static
(they are implicitly static)readonly
@nawfal 2013-12-13 20:21:44
They Can not be static, they are static. You should make it clear if you meant one can't declare
static const int i = 0;
@Minh Tran 2017-10-29 17:38:16
Can you explain why
const
declarations can't be made inside methods?@Yeasin Abedin Siam 2016-01-12 17:42:57
Read Only : Value can be changed through Ctor at runtime. But not through member Function
Constant : By defult static. Value cannot be changed from anywhere ( Ctor, Function, runtime etc no-where)
@Don Cheadle 2018-02-26 19:11:06
thanks for not making me read 4 paragraphs just for these two take-aways...
@Hallgrim 2008-09-17 13:02:06
They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.
Example:
@Gishu 2008-09-11 08:24:41
Apart from the apparent difference of
const
VSreadonly
values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen.static
. You use aClassName.ConstantName
notation to access them.There is a subtle difference. Consider a class defined in
AssemblyA
.AssemblyB
referencesAssemblyA
and uses these values in code. When this is compiled,const
value, it is like a find-replace, the value 2 is 'baked into' theAssemblyB
's IL. This means that if tomorrow I'll updateI_CONST_VALUE
to 20 in the future.AssemblyB
would still have 2 till I recompile it.readonly
value, it is like aref
to a memory location. The value is not baked intoAssemblyB
's IL. This means that if the memory location is updated,AssemblyB
gets the new value without recompilation. So ifI_RO_VALUE
is updated to 30, you only need to buildAssemblyA
. All clients do not need to be recompiled.So if you are confident that the value of the constant won't change use a
const
.But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a
readonly
.Update: Aku needs to get a mention coz he pointed this out first. Also I need to plug where I learned this.. Effective C# - Bill Wagner
@LCJ 2013-01-21 14:00:51
The
static
point seems to be the most important and useful point -consts are implicitly static
@CodingBarfield 2013-06-05 07:03:30
The part about reference values is the most important one. Const values can be optimized away.
@Bitterblue 2013-06-05 14:10:34
readonly
variables can be changed outside the constructor (reflection). It's only the compiler that tries to hinder you from modifying the var outside the constructor.@user743382 2014-04-14 11:55:40
@mini-me
readonly
variables are not allowed to be changed once the constructor has finished, even via reflection. The runtime happens to not enforce this. The runtime also happens not to enforce that you don't changestring.Empty
to"Hello, world!"
, but I still wouldn't claim that this makesstring.Empty
modifiable, or that code shouldn't assume thatstring.Empty
will always be a zero-length string.@user743382 2014-04-14 13:37:48
@mini-me That doesn't contradict what I said. They're not allowed to be changed, the CIL spec explicitly forbids it, but the runtime doesn't enforce it, and the CIL spec doesn't require (but does allow) the runtime to enforce it. Code modifying
readonly
fields is an active time bomb, just waiting to blow up when the runtime does start enforcing this.@CAD bloke 2014-08-05 21:52:55
blogs.msmvps.com/jonskeet/2014/07/16/… is an interesting read only the overhead cost of readonly
@dragan.stepanovic 2015-08-18 10:38:16
This is the same case as with method's default arguments. As with constants, their default value is embedded in the client's call, and if you change the value of the default argument in the method definition and recompile just that assembly, client assemblies will still have the old value.
@Nomi Ali 2017-03-23 09:11:34
what you mean by "BAKED", if you mean to say addition reference of AssemblyB into AssemblyA? if it is the case than const getting updated value.
@Gishu 2017-03-28 05:06:12
@NomiAli by Baked, i mean the value is embedded at each call site in the client code.. vs a reference to the value.
@Don Cheadle 2018-02-26 19:13:18
Read Only :
Value can be changed through Ctor at runtime. But not through member FunctionConstant :
By defult static. Value cannot be changed from anywhere ( Ctor, Function, runtime etc no-where)`@Mikhail 2019-02-11 14:19:26
"having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen" - can you please simplify this sentence? I read it like 5 times, but I still don't get it :(
@Vikram 2015-08-04 05:34:27
Constant
We need to provide the value to the const field when it is defined. The compiler then saves the constant’s value in the assembly’s metadata. This means that a constant can be defined only for the primitive type like boolean, char, byte and so on. Constants are always considered static members, not instance members.
Readonly
Readonly fields can only be resolved at runtime. That means we can define a value for a value using the constructor for the type in which the field is declared. The verification is done by the compiler that readonly fields are not written to by any method other than the constructor.
More about both explained here in this article
@Omar AMEZOUG 2015-04-09 21:09:25
Constant variables are declared and initialized at compile time. The value can’t be changed after wards. Read-only variables will be initialized only from the Static constructor of the class. Read only is used only when we want to assign the value at run time.
@Greg 2009-10-13 02:26:55
Yet another gotcha: readonly values can be changed by "devious" code via reflection.
Can I change a private readonly inherited field in C# using reflection?
@Chirag 2014-12-15 13:01:10
There is notable difference between const and readonly fields in C#.Net
const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.
readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -
Then readonly field can be initialised with instant specific values, as follows:
Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.
@Chris S 2009-01-31 11:42:05
Here's another link demonstrating how const isn't version safe, or relevant for reference types.
Summary:
@aku 2008-09-11 08:15:15
There is a gotcha with consts! If you reference a constant from another assembly, its value will be compiled right into the calling assembly. That way when you update the constant in the referenced assembly it won't change in the calling assembly!
@springy76 2016-08-19 13:02:01
On decompilation (Reflector, ILSpy, ..) a constant NEVER EVER is referenced by any one, no matter of same assembly or another assembly, so you cannot analyze the usage of a constant in compiled code at all.
@Yonatan Nir 2014-04-05 14:39:18
The difference is that the value of a static readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.
Remember: For reference types, in both cases (static and instance), the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
For details, please refer to C# Frequently Asked Questions on this topic: http://blogs.msdn.com/csharpfaq/archive/2004/12/03/274791.aspx
@donstack 2014-01-24 07:34:17
ReadOnly :The value will be initialized only once from the constructor of the class.
const: can be initialized in any function but only once
@Deepthi 2011-05-21 13:21:27
const
: Can't be changed anywhere.readonly
: This value can only be changed in the constructor. Can't be changed in normal functions.@Ramesh Rajendran 2013-09-28 08:19:52
Const and readonly are similar, but they are not exactly the same. A const field is a compile-time constant, meaning that that value can be computed at compile-time. A readonly field enables additional scenarios in which some code must be run during construction of the type. After construction, a readonly field cannot be changed.
For instance, const members can be used to define members like:
since values like 3.14 and 0 are compile-time constants. However, consider the case where you define a type and want to provide some pre-fab instances of it. E.g., you might want to define a Color class and provide "constants" for common colors like Black, White, etc. It isn't possible to do this with const members, as the right hand sides are not compile-time constants. One could do this with regular static members:
but then there is nothing to keep a client of Color from mucking with it, perhaps by swapping the Black and White values. Needless to say, this would cause consternation for other clients of the Color class. The "readonly" feature addresses this scenario. By simply introducing the readonly keyword in the declarations, we preserve the flexible initialization while preventing client code from mucking around.
It is interesting to note that const members are always static, whereas a readonly member can be either static or not, just like a regular field.
It is possible to use a single keyword for these two purposes, but this leads to either versioning problems or performance problems. Assume for a moment that we used a single keyword for this (const) and a developer wrote:
and a different developer wrote code that relied on A:
Now, can the code that is generated rely on the fact that A.C is a compile-time constant? I.e., can the use of A.C simply be replaced by the value 0? If you say "yes" to this, then that means that the developer of A cannot change the way that A.C is initialized -- this ties the hands of the developer of A without permission. If you say "no" to this question then an important optimization is missed. Perhaps the author of A is positive that A.C will always be zero. The use of both const and readonly allows the developer of A to specify the intent. This makes for better versioning behavior and also better performance.
@splattne 2008-12-02 11:50:14
Constants
Readonly instance fields
Static readonly fields
@Greg 2011-02-20 12:29:26
A
const
has to be hard-coded, where asreadonly
can be set in the constructor of the class.@Brett Ryan 2009-09-08 12:20:05
A constant will be compiled into the consumer as a literal value while the static string will serve as a reference to the value defined.
As an exercise, try creating an external library and consume it in a console application, then alter the values in the library and recompile it (without recompiling the consumer program), drop the DLL into the directory and run the EXE manually, you should find that the constant string does not change.
@ljs 2009-09-08 12:23:53
I sincerely doubt that is true... I will go check.
@Russ Cam 2009-09-08 12:24:56
this is one of the 50 specific ways to improve your C# - amazon.co.uk/Effective-Specific-Ways-Improve-Your/dp/0321245660/…
@Russ Cam 2009-09-08 12:27:32
my.safaribooksonline.com/0321245660/…
@ljs 2009-09-08 12:29:18
@Andrew Hare - yes, I just checked. I am very surprised, that is a real gotcha, I'm really very surprised by that, amazed that is the case...!
@ljs 2009-09-08 12:31:23
I do object, however, to the use of the word pointer here. It's not a pointer, it's a reference, and there is a difference in C# as you can manipulate unmanaged pointers in unsafe mode so it's important to distinguish between the two.
@ljs 2009-09-08 12:32:33
Not to mention the value itself is immutable, so you can't change it (well, not without some funky evil underhand manipulation). Anyway :)
@ljs 2009-09-08 12:24:24
Principally; you can assign a value to a static readonly field to a non-constant value at runtime, whereas a const has to be assigned a constant value.
@Wedge 2008-09-11 08:41:51
Variables marked const are little more than strongly typed #define macros, at compile time const variable references are replaced with inline literal values. As a consequence only certain built-in primitive value types can be used in this way. Variables marked readonly can be set, in a constructor, at run-time and their read-only-ness is enforced during run-time as well. There is some minor performance cost associated with this but it means you can use readonly with any type (even reference types).
Also, const variables are inherently static, whereas readonly variables can be instance specific if desired.
@Jason Baker 2009-01-05 22:35:21
Added that consts are strongly typed #define macros. Otherwise, we may scare off all the C or C++ people. :-)
@Mike Two 2008-10-19 22:14:57
There is a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.
@Scott Lawrence 2008-10-02 20:43:37
One of the team members in our office provided the following guidance on when to use const, static, and readonly:
One final note: a const field is static, but the inverse is not true.
@Michael Blackburn 2016-04-27 21:02:23
I think you mean "converse." The inverse would be "a non-const field is not static." Which may or may not be true. The converse, "a static field is (always) const" is not true.
@user1333 2008-09-11 10:37:04
Just to add, ReadOnly for reference types only makes the reference readonly not the values. For example:
@springy76 2016-08-19 13:02:57
Is there any other reference type than
string
that you could use as a constant?@Mike Rosoft 2018-04-27 14:28:40
You can have
const
with reference types other than string, but the constant can only have the valuenull
.@Mark T 2008-09-17 13:28:01
Another gotcha.
Since const really only works with basic data types, if you want to work with a class, you may feel "forced" to use ReadOnly. However, beware of the trap! ReadOnly means that you can not replace the object with another object (you can't make it refer to another object). But any process that has a reference to the object is free to modify the values inside the object!
So don't be confused into thinking that ReadOnly implies a user can't change things. There is no simple syntax in C# to prevent an instantiation of a class from having its internal values changed (as far as I know).
@Gishu 2008-09-17 13:31:27
Yes that is more of a general theme. If you have a get only property exposing an arraylist, you can still modify the arraylist. You cannot set a different arraylist to that property, but you cannot stop the user from altering the arraylist.
@AlanR 2008-09-15 21:30:19
The key difference is that Const is the C equivalent of #DEFINE. The number literally gets substituted a-la precompiler. Readonly is actually treated as a variable.
This distinction is especially relevant when you have Project A depending on a Public constant from Project B. Suppose the public constant changes. Now your choice of const/readonly will impact the behavior on project A:
Const: project A does not catch the new value (unless it is recompiled with the new const, of course) because it was compiled with the constants subtituted in.
ReadOnly: Project A will always ask project B for it's variable value, so it will pick up the new value of the public constant in B.
Honestly, I would recommend you use readonly for nearly everything except truly universal constants ( e.g. Pi, Inches_To_Centimeters). For anything that could possibly change, I say use readonly.
Hope this helps, Alan.
@Anthony 2008-09-15 10:14:17
One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g. readonly MaxFooCount = 5;)
But with a const, it would be folded into the caller's code when the caller was compiled.
If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C# Which answers this question in detail, (and 49 other things).
@Vinko Vrsalovic 2008-09-11 08:04:07
This explains it. Summary: const must be initialized at declaration time, readonly can be initialized on the constructor (and thus have a different value depending on the constructor used).
EDIT: See Gishu's gotcha above for the subtle difference