Simple question

  • Thread starter Thread starter count1986
  • Start date Start date
C

count1986

Why C# has "readonly field" and "const value", while Java has only
"final"?
Are there any reasons for doing so?
 
const is something that is better applied for true constants (the speed
of light, days of the week, number of seconds in a minute, etc, etc).

readonly is better suited for those things that require initialization,
which aren't necessarily known before the app is run. Good examples are the
local computer name, the startup time of a program, etc, etc. Basically,
things that won't change, but require some sort of work to find out when the
app is run.
 
Hi,

Extracted from MSDN :
Note The readonly keyword is different from the const keyword. A const
field can only be initialized at the declaration of the field. A
readonly field can be initialized either at the declaration or in a
constructor. Therefore, readonly fields can have different values
depending on the constructor used. Also, while a const field is a
compile-time constant, the readonly field can be used for runtime
constants as in the following example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;

@= http://msdn2.microsoft.com/en-us/library/acdd6hb7(VS.71).aspx
 
Why C# has "readonly field" and "const value", while Java has only
"final"?
Are there any reasons for doing so?

Well, in Java if you have a static final value which is of an
appropriate type (numeric or string, IIRC) it's treated in the same way
as "const" is in C# - i.e. the value is compiled into any code
referencing it, rather than the value being fetched at execution time.

Personally, I prefer the way that C# makes that explicit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top