Cheng Chen
Cheng Chen

Reputation: 43523

const vs. readonly

Today I found an article where a const field is called compile-time constant while a readonly field is called runtime constant. The two phrases come from 《Effective C#》. I searched in MSDN and the language spec, find nothing about runtime constant.

No offensive but I don't think runtime constant is a proper phrase.

private readonly string foo = "bar";

creates a variable named "foo", whose value is "bar", and the value is readonly, here it is a variable, no business on constant. A readonly variable is still a variable, it can't be a constant. Variable and constant are mutually exclusive.

Maybe this question goes overboard, still I want to listen to others' opinions. What do you think?

Upvotes: 12

Views: 10479

Answers (5)

Ala Eddine JEBALI
Ala Eddine JEBALI

Reputation: 7841

const vs readonly

This a complete resume comparison between const and readonly:

|-----------------------------------------|-----------------------------------------|
|              Constant Field             |             Read-only Field             |
|-----------------------------------------|-----------------------------------------|
| Compile-time constant                   | Run-time constant                       |
|-----------------------------------------|-----------------------------------------|
| Assigned to an expression evaluated at  | Assigned to any valid expression at     |
| compile time                            | runtime                                 |
|-----------------------------------------|-----------------------------------------|
| Assigned on declaration                 | Assigned on declaration or constructor  |
|-----------------------------------------|-----------------------------------------|
| Only number, Boolean or string          | Any data type                           |
|-----------------------------------------|-----------------------------------------|
| Always static                           | Optionally static                       |
|-----------------------------------------|-----------------------------------------|

Explanation

  • Constants are static (no need to instantiate the class to access them).
  • Constants can only be assigned on declaration.
  • Constants are compile-time constant because they are assigned to an expression evaluated at compile time: when they changed, the project should be recompiled to use the new values.
  • Read-Only Fields are variables in a class which hold a value that is initialized (only in the constructor or in the declaration) and then not changed.
  • Read-Only Fields are Runtime constant because they can be assigned to any valid expression at runtime.
  • A Read-Only Field apply to the instance of the object but not the property of that instance. So other code can change the instance property of read-only field.
  • Read-Only Fields are optionally static (if you want to make them shared by all instances).

When to use const and when to use readonly ?

  • Constants are useful when they are of simple type and their values will never be changed.
  • Read-Only Fields are useful when they are initialized from a source (file, database or other codes, ..etc.) but then they will not be changed.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062865

As you yourself note, that term is not used in the language specification etc. So; blame that book! I would call it a "readonly field", because that is what it is - where the definition of "readonly" here relates to the initializer/constructor, and is limited to regular code. For example, even readonly fields are changeable...

// how to annoy your colleagues...
typeof(string).GetField("Empty").SetValue(null, " ");

(Note, this no longer works on recent CLR versions - the JIT presumably replaces the field-load with a ldstr - but it genuinely did for a very long time)

(more genuine reasons to do this on objects relate to deserialization)

Upvotes: 7

Tigran
Tigran

Reputation: 62256

I believe that author means the following:

Consider example:

public class A {

     public const int a = Compute();         

     private static int Compute(){

          /*some computation and return*/ 
          return some_computed_value;
     }
}

this, will not compile, as you have to have constant value to assign to a . So this is a meaning of compile-time constant .

Instead if you change this to

public class A {

     public readonly int a = Compute();          

     private static int Compute(){
          /*some computation and return*/ 
          return some_computed_value;
     }
}

this will compile. It at runtime makes a computation and assign it to a. This is a meaning of runtime constant

Upvotes: 10

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

I would call readonly a "write once variable", which is checked by the compiler, not at runtime. You could write the field using reflection, so it is not constant at runtime.

Upvotes: 2

Ryan Amies
Ryan Amies

Reputation: 4922

A readonly variable can only be changed in its constructor and can be used on complex objects. A constant variable cannot be changed at runtime, but can only be used on simple types like Int, Double, String. Runtime constant is somewhat accurate, but confuses the issue, there are very explicit differences between a constant and a readonly, and so naming one similar to another is probably not a good idea, even though often they are used to the same purpose.

A quick summary of the differences here

Upvotes: 2

Related Questions