473,412 Members | 2,096 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,412 software developers and data experts.

What is the difference between: readonly and const

I am reading something about the details of C#, and I came acros the
statements readonly and const. I do not understand, it seems to be the same,
what's the difference? Here is the text were it refers to:

const long size = ((long)int.MaxValue + 1) / 4;

Constant-Value must be computable at compile time

readonly DateTime date;

Read Only Field-Must be initialized in their declaration or in a
constructor-Value needs not be computable at compile time-Consumes a memory
location (like a field)

(Or it should be the latter, that const is created on the stack and readonly
on the heap??)
Nov 17 '05 #1
13 5986
Hi My4thPersonality,

const needs to be set at compile time while readonly can be generated
dynamically in a constructor, but you can set it only once.

readonly int readonlyInt;
const int constint = 0;

public MyClass(int n)
{
readonlyInt = n;
}
--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #2
My4thPersonality <so*******@out.there> wrote:
I am reading something about the details of C#, and I came acros the
statements readonly and const. I do not understand, it seems to be the same,
what's the difference? Here is the text were it refers to:

const long size = ((long)int.MaxValue + 1) / 4;

Constant-Value must be computable at compile time

readonly DateTime date;

Read Only Field-Must be initialized in their declaration or in a
constructor-Value needs not be computable at compile time-Consumes a memory
location (like a field)

(Or it should be the latter, that const is created on the stack and readonly
on the heap??)


Const is compiled directly into the code - if you write

const long Size = 100; // or whatever

then later

int x = Size;

it compiles the declaration/assignment of x as

int x = 100;

rather than as a run-time reference to the Size member.

It's not really got anything to do with stack/heap.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3

"Morten Wennevik" <Mo************@hotmail.com> schreef
const needs to be set at compile time while readonly can be generated
dynamically in a constructor, but you can set it only once.


Thanks for the quick answer!
Nov 17 '05 #4
"My4thPersonality" <so*******@out.there> wrote in message
news:eY**************@TK2MSFTNGP14.phx.gbl...
I am reading something about the details of C#, and I came acros the
statements readonly and const. I do not understand, it seems to be the same, what's the difference? Here is the text were it refers to:

const long size = ((long)int.MaxValue + 1) / 4;

Constant-Value must be computable at compile time

readonly DateTime date;

Read Only Field-Must be initialized in their declaration or in a
constructor-Value needs not be computable at compile time-Consumes a memory location (like a field)

(Or it should be the latter, that const is created on the stack and readonly on the heap??)


Hello -

I know of one difference regarding versioning - if you write a DLL in C#
that defines constants, then the values of those constants will be
hard-coded into applications that call the DLL at compile time, and the DLL
is not called at runtime when the constant is referenced. This causes
problems if you're not using strong versioning and you produce a new
version of the DLL containing different constant values and just
xcopy-deploy it without recompiling the calling application. readonly fields
don't suffer from this problem.

Regards,

Simon
Nov 17 '05 #5

"Simon Shearn" <si***@sgurr.theredwire.co.uk> schreef
I know of one difference regarding versioning - if you write a DLL in C# .... don't suffer from this problem.


Was this actually the reason why they introduced the readonly variable? I
know C++, and I cannot think of a simular keyword for this in C++. Perhaps
it's just that my C++ knowlegde is not perfect, or it could be that the
readonly variable was convenient on the .NET platform especially, for this
versioning problem. (Just curious about this.)
Nov 17 '05 #6
> readonly can be generated dynamically
in a constructor, but you can set it only once.


Here's a trivial point: readonly can be set multiple times, but it can only
be done with a variable initializer (inline) or within the constructor.
Nov 17 '05 #7
> I am reading something about the details of C#, and I came acros the
statements readonly and const. I do not understand, it seems to be the same,
what's the difference?


This is actually a pretty complicated issue. Here are a couple of points
which might help you choose between them.

const is only useful for the predefined types like int, double, char, etc.
const has to be given a value at compile time and these are the only things
where you have a compile-time constant (17, 3.14, 'A', etc.).

const does work for string since we also have a literal for that (string s =
"hello";) but it is rarely done in practice since it applies to the reference
and not the object and the data inside a string is already immutable.

If you are using a struct that is not a predefined type (DateTime, TimeSpan,
etc.) then readonly is your only option. You can't use const since you don't
have a compile-time literal for them.
Nov 17 '05 #8

"My4thPersonality" <so*******@out.there> wrote in message
news:OD*************@TK2MSFTNGP15.phx.gbl...

"Simon Shearn" <si***@sgurr.theredwire.co.uk> schreef
I know of one difference regarding versioning - if you write a DLL in C# ...
don't suffer from this problem.


Was this actually the reason why they introduced the readonly variable? I
know C++, and I cannot think of a simular keyword for this in C++. Perhaps
it's just that my C++ knowlegde is not perfect, or it could be that the
readonly variable was convenient on the .NET platform especially, for this
versioning problem. (Just curious about this.)


In Java (C# is strongly inspired from Java), you can qualify a field with
"final" and the semantics are the same as when you qualify with "readonly"
in C#. On the other hand, Java does not have any "const" keywork. So, C#
borrowed const from C++ and readonly from Java!

Bruno.

Nov 17 '05 #9
MarkT [developmentor] <Ma****************@discussions.microsoft.com>
wrote:
I am reading something about the details of C#, and I came acros the
statements readonly and const. I do not understand, it seems to be the same,
what's the difference?


This is actually a pretty complicated issue. Here are a couple of points
which might help you choose between them.

const is only useful for the predefined types like int, double, char, etc.
const has to be given a value at compile time and these are the only things
where you have a compile-time constant (17, 3.14, 'A', etc.).

const does work for string since we also have a literal for that (string s =
"hello";) but it is rarely done in practice since it applies to the reference
and not the object and the data inside a string is already immutable.


The same would be true for all the primitive types though. I find that
const strings are quite common, actually. Other than versioning
reasons, there are few reasons to make a string variable readonly
instead of const in cases where you can use const.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> schreef
In Java (C# is strongly inspired from Java), you can qualify a field with
"final" and the semantics are the same as when you qualify with "readonly"
in C#.


I thought you could compare the keyword sealed in C# to final in Java? Or is
that valid for classes and virtual functions, and you can compare final for
a field with readonly?
Nov 17 '05 #11

"My4thPersonality" <so*******@out.there> wrote in message
news:u8***************@TK2MSFTNGP12.phx.gbl...

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> schreef
In Java (C# is strongly inspired from Java), you can qualify a field with
"final" and the semantics are the same as when you qualify with
"readonly" in C#.
I thought you could compare the keyword sealed in C# to final in Java? Or
is that valid for classes and virtual functions, and you can compare final
for a field with readonly?


Yes, final has many usages in Java
final applied to class or method corresponds to sealed in C#
final applied to field corresponds to readonly in C#

And Java also lets you apply final to a local variable, in which case, it
corresponds more or less to C++'s const. For example:
final int foo = some_expression; // local variable declaration, foo
cannot be reassigned.

Nov 17 '05 #12

"Bruno Jouhier [MVP]" <bj******@club-internet.fr> schreef
Yes, final has many usages in Java

.....

Thanks! I think learning Java, C#, and comparing it to C++ really learns me
a lot and gives me opportunities, so I must say this ng and your answers are
helping me a lot!!
Nov 17 '05 #13
> Yes, final has many usages in Java

there's one more: final parameter in Java (which mostly gets used with
anonymous classes).
Nov 17 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: cppsks | last post by:
namespace test { static const int num = 10; const int num2 = 20; } What exactly is the difference here? Which is preferred (if both mean the same)?
11
by: modemer | last post by:
If I define the following codes: void f(const MyClass & in) {cout << "f(const)\n";} void f(MyClass in) {cout<<"f()\n";} MyClass myclass; f(myclass); Compiler complain that it can't find...
2
by: diadia | last post by:
string s = "hello"; const char *p = s.begin(); cout << p << endl; // print hello s = ""; char *p2= s.begin(); cout << p2 << endl; // print hello why?????
7
by: xgngli | last post by:
Hi all! I've taken some time on learning the difference between "pointers to const variables" and "const pointer variables". The question is: in the following code, can we change the contents of...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.