Is there a difference between const and private readonly private variables in C #?

Is there a difference between having a private const variable or a private static readonly variable in C # (other than having to assign a const compilation expression)?

Since they are both private, there is no link to other libraries. So will it make any difference? Could this make a difference in performance, for example? Interned strings? Anything like that?

+26
c # const readonly
Jan 04 '09 at 9:24
source share
9 answers

Well, you can use consts in attributes as they exist as compile time. You cannot predict the value of the readonly static variable since .cctor can initialize it from the configuration, etc.

In terms of usage, constants are burned in the calling code. This means that if you recompile the dll library to change the public constant, but do not change consumers, then consumers will still use the original value. With the readonly variable, this will not happen. This means that constants (very, very little) are faster because they just load the value (instead of de-referencing it).

Re-internment; although you can do it manually, it is most often the compiler / runtime function of literals; if you initialize the readonly field via a literal:

 someField = "abc"; 

then "abc" will be interned. If you read it from config, this will not happen. Since the constant string must be literal, it will also be interned, but it will be accessed differently: reading from the field again is a de-link, not ldstr .

+29
Jan 04 '09 at 9:37
source share

Indeed, these two types cannot be changed after they are initialized, but there are some differences between them:

  • 'const' must be initialized where it is declared (at compile time), while readonly can be initialized where it is declared or inside the constructor (ar runtime).

For example, const can be used in this situation:

 public class MathValues { public const double PI = 3.14159; } 

And for reading it would be better:

 public class Person { public readonly DateTime birthDate; public Person(DateTime birthDate) { this.birthDate = birthDate; } } 

or

 public class Person { public readonly DateTime birthDate = new DateTime(1986, 1, 24); } 
  • 'const' is static, so it is shared between all instances of this class and can be accessed directly (for example, MathValues.PI), while "readonly" is not static. As a result, a declaration like “static const” is illegal because const is static, but “static readonly” is legal.

  • 'const' can only contain an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool or string), an enumeration, or a reference to zero (not classes or structures, because they are initialized at runtime, with the keyword “new”), whereas “readonly” can contain complex types, structures, or classes (using the new keyword at initialization), but cannot contain enumerations

+10
Jan 04 '09 at 10:09
source share

Something to remember about constants, they are actually stored in your executable file, so declaring many of them will increase the size of the executable file.

Usually this is not a big problem, but my friend worked for a company that applied the rule “everything should be const” and managed to significantly increase its compiled executable size.

+4
Jan 04 '09 at 9:31
source share

In use? Not really. Consts are evaluated at compile time, while readonly are evaluated at runtime. You can also set the readonly variable to a value in the constructor.

+2
Jan 04 '09 at 9:28
source share

Here are the differences between the C # .NET const, readonly, and static readonly fields (from from this article ).

Constants

  • Static default
  • Must have a compile time value (i.e. you can have "A" + "B" but you cannot have method calls)
  • Can be used in attributes
  • They are copied to each assembly that uses them (each assembly receives a local copy of the values)
  • May be declared inside functions

Readonly instance fields :

  • Evaluated on instantiation
  • Must be set using the time constructor

Read-only static fields :

  • Evaluated when code execution hits a class reference (i.e.: a new instance is created or a static method is executed)
  • The time value when the static constructor is executed must be evaluated.
  • You really do not want to put ThreadStaticAttribute on them (since the static constructor will only run on one thread and it will set a value for its thread, all other threads will have this value uninitialized)
+2
Jan 04 '09 at 14:31
source share

Significant difference between const and readonly fields in C # .Net

const is static by default and must be initialized with a constant value, which cannot be changed later. Changing the value is also not allowed in the constructors. It cannot be used with all data types. For ex-DateTime. It cannot be used with the DateTime data type.

 public const DateTime dt = DateTime.Today; //throws compilation error public const string Name = string.Empty; //throws compilation error public readonly string Name = string.Empty; //No error, legal 

readonly can be declared as static, but optional. No need to initialize during declaration. Its value can be assigned or changed using the constructor. Thus, it provides an advantage when used as a member of an instance class. Two different instances may have a different readonly value. For ex -

 class A { public readonly int Id; public A(int i) { Id = i; } } 

The readonly field can then be initialized with instant specific values ​​as follows:

 A objOne = new A(5); A objTwo = new A(10); 

Here, the objOne instance will have a readonly field value of 5, and objTwo will have 10. This is not possible with const.

+2
Dec 15 '14 at 12:54
source share

One more thing. I did not see this in the comments above, although I might have missed it. You cannot create a permanent array.

 private const int[] values = new int[] { 1, 2, 3 }; 

But you can create it using readonly static field.

 private static readonly int[] values = new int[] { 1, 2, 3 }; 

So, if you need an array constant, such as a list of valid values, and an enumeration is not suitable, then static readonly is the only way to go. For example, if the array has zero integers, for example:

 private static readonly int?[] values = new int?[] { null, 1, 2, 3 }; 

I can not do this with a constant, maybe I?

+1
Apr 16 '09 at 12:45
source share

Readonly fields can be initialized either in the declaration or in the class constructor. Therefore, readonly fields can have different values ​​depending on the constructor used .

The readonly element can also be used for runtime constants , as in the following example:

 public static readonly uint currentTicks = (uint)DateTime.Now.Ticks; 

The readonly fields are not implicitly static, and therefore a static keyword can (should) be applied to the readonly field explicitly, if necessary. This is not valid for constant fields that are implicitly static.

Readonly members can contain complex objects using the new keyword during initialization.

0
Jan 04 '09 at 10:10
source share

The difference is that the value of the readonly static field is set at run time and therefore can be changed using the containing class, while the value of the constant field is set to a compile time constant.

In the static readonly case, the contained class is only allowed to modify it

in a variable declaration (via a variable initializer) in a static constructor (instance constructors if they are not static) static readonly is usually used if the field type is not allowed in the const declaration or when the value is unknown at compile time.

Readonly instance fields are also available.

Remember that for reference types in both cases (static and instance), the readonly modifier only prevents you from assigning a new link to this field. It does not specifically make the object referenced by it immutable.

 class Program { public static readonly Test test = new Test(); static void Main(string[] args) { test.Name = "Program"; test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) } } class Test { public string Name; } 



The difference is that read-only static access can be changed using the containing class, but the constant can never be changed and must be initialized until the compile time constant. To expand in the static case a read-only bit, the containing class can only change it:

- in the variable declaration (via the variable initializer).

- in a static constructor (instance constructors, if it is not static).




Keyword Const in C # .NET

Example: public const string abc = "xyz"; It is initialized only at the announcement. The value is evaluated at compile time and cannot be changed at run time. Attempting to change it will cause a compilation error. Constants are already static. Since classes and structures are initialized at run time with the new keyword, you cannot set a constant to a class or structure. But it must be one of the integral types. Readonly keyword in C # .NET

Example: public readonly string abc; It can be initialized in the declaration code or in the consturctor code. The value is evaluated at runtime. May be declared as static or instance level attribute. A read-only field can contain a complex object using the new keyword at run time.

0
Apr 03 '09 at 8:55
source share



All Articles