The usage and difference between static constants (const) and dynamic constants (static and readonly) in C#

There are two constant types in C#, namely readonly (runtime constant) and const (compile time constant). This article will compare the different characteristics of these two types and explain their applicable scenarios.
The working principle of
readonly is a runtime constant, which is assigned when the program is running, and cannot be changed after the assignment is completed, so it is also called a read-only variable.
const is a compile-time constant, the constant value will be parsed when the program is compiled, and all constant references will be replaced with corresponding values.
Two constants are declared below:

public  static  readonly  int A = 2 ; // A is a runtime constant 
public  const  int B = 3 ; // B is a compile-time constant

The following expression:

int C = A + B;

 


After compilation, it is equivalent to the following form:

int C = A + 3;

 


It can be seen that the const constant B is replaced by the literal 3, while the readonly constant A remains referenced.
Declaration and initialization
readonly constants can only be declared as class fields, support instance types or static types, can be initialized at the same time as declaration or in the constructor, and cannot be changed after initialization is complete.
In addition to being declared as a class field, a const constant can also be declared as a local constant in a method. The default is a static type (no need to be modified with static, otherwise it will cause a compilation error), but the initialization must be completed at the same time as the declaration.

Data type support
Since const constants will be replaced by literals at compile time, their value types are limited. Const constants can only be assigned to numbers (integers, floats), strings, and enumeration types. The following code fails to compile:

public const DateTime D = DateTime.MinValue;

Change to readonly to compile normally:

1 public readonly DateTime D = DateTime.MinValue;

Maintainability
Readonly works by reference. After a constant is updated, all places that refer to the constant can get the updated value.
The const case is slightly more complicated, especially for cross-assembly calls:

1  public  class Class1
 2  {
 3      public  static  readonly  int A = 2 ; // A is a runtime constant 
4      public  const  int B = 3 ; // B is a compile-time constant 
5  }
 6  
7  public  class Class2
 8  {
 9      public  static  int C = Class1.A + Class1.B; // The value of variable C is the sum of A and B 
10  }
 11  
12 Console.WriteLine(Class2.C); // Output "5"

 

Assuming that Class1 and Class2 are in two different assemblies, now change the constant value in Class1:

1  public  class Class1
 2  {
 3         public  static  readonly  int A = 4 ; // A is a runtime constant 
4         public  const  int B = 5 ; // B is a compile-time constant 
5 }

Compile Class1 and deploy (note: Class2 is not recompiled at this time), and check the value of variable C again:

1 Console.WriteLine(Class2.C); //输出"7"

The result may be a little unexpected, let's take a closer look at the assignment expression of variable C:

public static int C = Class1.A + Class1.B;

After compilation, it is equivalent to the following form:

public static int C = Class1.A + 3;

Therefore, no matter how the value of constant B changes, it will not affect the final result. Although recompiling Class2 can solve this problem, but at least let us see the maintenance problems that const may bring.

Performance comparison
const directly participates in operations in the form of literals, and the performance is slightly higher than readonly, but for general applications, the difference in performance can be said to be minimal.

Applicable scenarios
In the following two cases:
a. The value is permanently unchanged (such as pi, the number of hours contained in a day, the radius of the earth, etc.)
b. The program performance requirements are very demanding
, and const constants can be used, in addition to other In all cases, readonly constants should be preferred.

 

static in C# and static in Java

Simple, the usage of the two is exactly the same. Discuss from two aspects:

1. Variables belong to the class, not the instance level. It can only be called by the class name, not by the instance.

2. If the assignment is made at the time of definition, then when the class is initialized, the assignment of all static variables is completed first. Note, however, that the initialization order of all static variables cannot be determined.

 

const in C# and finnal in Java

For a long time I have always thought that the two have the same effect, nothing more than that the variable cannot be changed after initialization, that is, it can only be assigned at the time of definition or in the constructor. However, this is only one-sided, the following will give you a detailed analysis:

1. Modified variables

To be precise, const in C# is equivalent to static final in Java, that is to say, final in Java does not have the function of static. And const in C# has the function of static. So in C# public static const string etc will be public const string.

2. Modified classes and methods

At this time, final in Java is similar to sealed in C#, that is to say, final-modified classes cannot be inherited, and final-modified methods cannot be overridden.

In C#, const cannot modify classes and methods.

question:

1. The role of private static members (private static variables)

Literally means private and cannot be used outside the class; static, global variables. It seems very contradictory, and it cannot be used outside the class. What is the use of globalization. Good question, it also makes sense to be global in a class, such as private static int a = 5, then you can guarantee that the variable a will be initialized first during the initialization of the class (before the constructor is executed). In this way, if the initialization of object A requires an instance of object B, then this declaration can be used to ensure that the instance of class B can be used in the constructor of class A. At the same time, private can ensure that instances of class B can only be used in class A, which plays a good sealing role.

2. The role of private final members (private final variables)

This member must be initialized before the class constructor completes, and once defined, it cannot be changed; this member can only be used in this class. Instances and subclasses cannot be used.

A member modified by private static final is assigned a value when it is declared to ensure that it can be used in the constructor. A member modified by private static final usually represents an instance of other components, and the variable is a global variable in the class.

The private final modified member is assigned in the construction, indicating that it is a global private member variable of the class, and the construction of the class needs to pass in their initial values ​​to complete the initialization of the class.


 

Difference between C# const and static readonly

const: A member declared with the const modifier is called a constant, which is initialized at compile time and embedded in the client program 
static readonly: A member declared with the static readonly modifier is still a variable, but it has a similar usage method as a constant: through the class It cannot be modified after access and initialization. But unlike constants, such variables are initialized at runtime.

Example of the difference between C# const and static readonly:

 1 using System;  
 2 using System.Collections.Generic;  
 3 using System.Text;  
 4    
 5 namespace Example02Lib  
 6 {  
 7      public class Class1  
 8      {  
 9             public const String strConst = "Const";  
10             public static readonly String strStaticReadonly = "StaticReadonly";  
11             //public const String strConst = "Const Changed";  
12             //public static readonly String strStaticReadonly = "StaticReadonly Changed";  
13      }  
14 } 

Client code:

1  using System;  
 2  using System.Collections.Generic;  
 3  using System.Text;  
 4  using Example02Lib;   
 5  namespace Example02  
 6  {  
 7       class Program  
 8       {  
 9             static  void Main( string [] args)  
 10             {  
 11                    // Modify in Example02 After the initial value of strConst of Class1, only compile the Example02Lib project  
 12                    // Then go to the resource manager and copy the newly compiled Example02Lib.dll to the directory where Example02.exe is located, and execute Example02.exe  
 13                   //Never debug and run directly in the IDE as this will recompile the entire solution! !   
14                    // You can see that the output of strConst has not changed, while the output of strStaticReadonly has changed  
 15                   // Indicates that the Const variable is initialized at compile time and embedded in the client program, while StaticReadonly is initialized at runtime   
16                  Console.WriteLine( " strConst : {0} " , Class1.strConst);  
 17                  Console.WriteLine( " strStaticReadonly : {0} " , 
 18                  Class1.strStaticReadonly);   
 19                  Console.ReadLine();  
 20            }  
 21       }  
 22 }

Modified example:

 1 using System;  
 2 using System.Collections.Generic;  
 3 using System.Text;  
 4    
 5 namespace Example02Lib  
 6 {  
 7        public class Class1  
 8        {  
 9              //public const String strConst = "Const";  
10              //public static readonly String strStaticReadonly = "StaticReadonly";  
11              public const String strConst = "Const Changed";  
12              public static readonly String strStaticReadonly = "StaticReadonly Changed";  
13        }  
14 } 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325739639&siteId=291194637