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

后端 未结 9 1014
鱼传尺愫
鱼传尺愫 2020-12-29 03:04

Is there a difference between having a private const variable or a private static readonly variable in C# (other than having to assign the co

相关标签:
9条回答
  • 2020-12-29 03:13

    The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

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

    in the variable declaration (through a variable initializer) in the static constructor (instance constructors, if it's not static) static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

    Instance readonly fields are also allowed.

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

    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 static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it:

    -- in the variable declaration (through a variable initializer).

    -- in the static constructor (instance constructors if it's not static).


    Const Keyword in C# .NET

    Example: public const string abc = “xyz”; Initialized only at declaration. Value is evaluated at compile time and can not be changed at run time. An attempt to change it will cause a compilation error. Const is already kind of static. Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types. Readonly Keyword in C# .NET

    Example: public readonly string abc; Can be initialized in declaration code or consturctor code. Value is evaluated at run time. Can be declared as static or instance level attribute. A read only field can hold a complex object by using the new keyword at run time.

    0 讨论(0)
  • 2020-12-29 03:14

    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)
    0 讨论(0)
  • 2020-12-29 03:24

    One more thing. I didn't see this in the comments above, although I may have missed it. You cannot create a constant array.

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

    But you can create it using a static readonly field.

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

    So if you need an array constant, such as a list of allowable values, and an enumeration would not be appropriate, then the static readonly is the only way to go. For instance, if the array were of nullable integers, like this:

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

    Can't do that with a constant, can ya?

    0 讨论(0)
  • 2020-12-29 03:25

    There is notable difference between const and readonly fields in C#.Net

    const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.

    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 not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -

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

    Then readonly field can be initialised with instant specific values, as follows:

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

    Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.

    0 讨论(0)
  • 2020-12-29 03:26

    Something to note about constants is they're actually stored in your executable, so declaring a lot of them will increase your executable file size.

    Normally, this isn't a huge problem, but a friend of mine worked at company that enforced an "everything must be const" rule and managed to significantly increase their compiled executable size.

    0 讨论(0)
  • 2020-12-29 03:26

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

    A readonly member can also be used for runtime constants as in the following example:

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

    Readonly fields are not implicitly static, and therefore the static keyword can (must) be applied to a readonly field explicitly if required. This is not allowed for const fields, which are implicitly static.

    Readonly members can hold complex objects by using the new keyword at initialization.

    0 讨论(0)
提交回复
热议问题