Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between private const and private readonly 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 the const a compile-time expression)?

Since they are both private, there is no linking with other libraries. So would it make any difference? Can it make a performance difference for example? Interned strings? Anything similar?

like image 855
Hosam Aly Avatar asked Jan 04 '09 09:01

Hosam Aly


People also ask

What is the difference between constants and read-only variables?

The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.

Are const variables read-only?

const field value cannot be changed after declaration. readonly fields cannot be defined within a method. const fields can be declared within a method. readonly variables are declared as instance variable and assigned values in constructor.

What is difference between static constant and readonly variables?

Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor. Constant variables cannot be modified after declaration. Static members can be accessed using ClassName.

What is the difference between const readonly and static keyword?

Constant and ReadOnly keyword is used to make a field constant which value cannot be modified. The static keyword is used to make members static that can be shared by all the class objects.


3 Answers

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

In terms of usage, constants are burnt into the calling code. This means that if you recompile a library dll to change a public constant, but don't change the consumers, then he consumers will still use the original value. With a readonly variable this won't happen. The flip of this is that constants are (very, very slightly) quicker, since it simply loads the value (rather than having to de-reference it).

Re interning; although you can do this manually, this is most commonly a compiler/runtime feature of literals; if you init a readonly field via a literal:

someField = "abc";

then the "abc" will be interned. If you read it from config, it won't be. Because a constant string must be a literal, it will also be interned, but it is accessed differently: again, reading from the field is a de-reference, rather than a ldstr.

like image 113
Marc Gravell Avatar answered Oct 25 '22 23:10

Marc Gravell


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

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

For example const could be used in this situation:

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

And readonly would be better for this case:

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 that class and can be accessed directly (like MathValues.PI), whereas 'readonly' is not static. As a consequence a declaration like 'static const' is illegal because const is static, but 'static readonly' is legal

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

like image 41
melculetz Avatar answered Oct 25 '22 22:10

melculetz


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

Constants:

  • Static by default
  • Must have compilation-time value (i.e.: you can have "A"+"B" but cannot have method calls)
  • Can be used in attributes
  • Are copied into every assembly that uses them (every assembly gets a local copy of values)
  • Could be declared within functions

Readonly instance fields:

  • Are evaluated when instance is created
  • Must have set value by the time constructor exits

Static readonly fields:

  • Are evaluated when code execution hits class reference (i.e.: new instance is created or static method is executed)
  • Must have evaluated value by the time static constructor is done
  • You really do not want to put ThreadStaticAttribute on these (since static constructor will be executed in one thread only and it will set value for its thread; all other threads will have this value uninitialized)
like image 21
Rinat Abdullin Avatar answered Oct 25 '22 21:10

Rinat Abdullin