Simple question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • count1986@gmail.com

    #1

    Simple question

    Why C# has "readonly field" and "const value", while Java has only
    "final"?
    Are there any reasons for doing so?

  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Simple question

    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.

    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    <count1986@gmai l.comwrote in message
    news:1190482660 .710979.167840@ 19g2000hsx.goog legroups.com...
    Why C# has "readonly field" and "const value", while Java has only
    "final"?
    Are there any reasons for doing so?
    >

    Comment

    • Martin CLAVREUIL

      #3
      Re: Simple question

      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.Ti cks;

      @= http://msdn2.microsoft.com/en-us/lib...b7(VS.71).aspx

      count1986@gmail .com wrote:
      Why C# has "readonly field" and "const value", while Java has only
      "final"?
      Are there any reasons for doing so?
      >

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: Simple question

        <count1986@gmai l.comwrote:
        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.

        --
        Jon Skeet - <skeet@pobox.co m>
        http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
        If replying to the group, please do not mail me too

        Comment

        Working...