Comparison of static, readonly, and const in C #

Source: Internet
Author: User
C # has two constant types: readonly (runtime constant) and const (compilation constant ), this article compares the two types of features and describes their application scenarios. Working principle readonly refers to the number of running times, which is assigned a value when the program is running. After the assignment is completed, it cannot be changed. Therefore, some people call it a read-only variable. Const is the compile-time constant. During program compilation, constant values are parsed and all constant references are replaced with corresponding values. The following two constants are declared: public static readonly int A = 2; // A indicates the runtime constant public const int B = 3; // B indicates the following expression during compilation: int c = a + B; after compilation, it is equivalent to the following form: int c = a + 3; you can see that the const constant B is replaced with the word surface 3, while readonly constant A maintains the reference mode. The declaration and initialization of readonly constants can only be declared as class fields. The instance type or static type is supported. It can be initialized at the same time as the declaration or initialized in the constructor. After the initialization is complete, it cannot be changed. In addition to being declared as a class field, const constants can also be declared as local constants in methods. The default value is static type (without static modification; otherwise, compilation errors will occur ), however, initialization must be completed at the same time as the declaration. The data type is supported because the const constant will be replaced with the literal value during compilation, which limits its value type. Const constants can only be assigned numbers (integers, floating-point numbers), strings, and enumeration types. The following code cannot be compiled: Public const datetime d = datetime. minvalue; changed to readonly for normal Compilation: Public readonly datetime d = datetime. minvalue; maintainability readonly works in reference mode. After a constant is updated, all the places that reference the constant can get the updated value. Const is a little more complex, especially for cross-assembly calls: public class class1 {public static readonly int A = 2; // A indicates the runtime constant public const int B = 3; // B is the compile time.} public class class2 {public static int c = class1.a + class1. B; // The value of variable C is the sum of a and B} console. writeline (class2.c); // output "5" Assume that class1 and class2 are in two different sets. Now, change the constant value in class1: public class class1 {public static readonly int A = 4; // A indicates the runtime constant public const int B = 5; // B indicates the compilation constant} compiles class1 and deploys it (Note: At this time, no Re-compile class2), and check the value of variable C again: console. writeline (class2.c); // The output result of "7" may be somewhat unexpected. Let's take a closer look at the value assignment expression of variable C: public static int c = class1.a + class1. B; it is equivalent to the following form after compilation: 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 re-compiling class2 can solve this problem, at least we can see the possible maintenance problems caused by const. Const performs computation in a literal way, and its performance is slightly higher than readonly. However, for general applications, the performance difference is negligible. The applicable scenarios are as follows:. the value is permanently unchanged (such as the circumference rate, the number of hours in a day, and the Earth's radius) B. const constants can be used for demanding program performance. In other cases, readonly constants should be used first.

 

 

Static in C # and static in Java

Simple. The two are used in the same way. The following two aspects are discussed:

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

2.If the value is assigned during definition, the assignment of all static variables is completed first during class initialization. However, the initialization sequence 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 functions are the same, but they cannot be changed after variable initialization, that is, they can only be assigned values at the time of definition or in the constructor. However, this is only one-sided. We will analyze it in detail below:

1. Modify Variables

To be accurate, const in C # is equivalent to static final in Java. That is to say, final in Java does not have static functions. Const in C # has the static function. Therefore, in C #, public static const string will be set to public const string.

2. modifier classes and Methods

In this case, final in Java is similar to sealed in C #. That is to say, the final-modified class cannot be inherited, and the final-modified method cannot be overwritten.

Const in C # Cannot modify classes and methods.

Problem:

1.Role of Private Static members (Private static variable)

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

2.Private final Member)

Before the class constructor is complete, the member must be initialized. Once defined, the member cannot be changed. The member can only be used in this class. Instances and subclasses cannot be used.

Members modified by Private Static final are assigned a value during the Declaration to ensure that they can be used in the constructor. A member modified by Private Static final usually represents an instance of other components, and the variable is the global variable in the class.

The private final modified member is assigned a value in the constructor, indicating that it is a global private member variable of the class. The constructor needs to input their initial values to complete class initialization.

C # difference between const and static readonly

Const: The member declared with the const modifier is called a constant, Which is initialized during compilation and embedded into the client program.
Static readonly: The member declared with the static readonly modifier is still a variable, but it has a usage similar to a constant: it can be accessed through a class and cannot be modified after initialization. But unlike constants, these variables are initialized at runtime.

C # example of difference between 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. }  

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. // After modifying the initial strconst value of class1 in example02, compile only the example02lib Project
  12. // Check the newly compiled example02lib.dllbeibeibeibeiexample02.exe.pdf in the resource manager to execute example02.exe.
  13. // Do not directly debug and run in IDE because this will recompile the entire solution !!
  14. // You can see that the output of strconst has not changed, and the output of strstaticreadonly has changed
  15. // Indicates that the const variable is initialized and embedded in the client program during the compilation period, while staticreadonly is initialized at the runtime.
  16. Console. writeline ("strconst: {0}", class1.strconst );
  17. Console. writeline ("strstaticreadonly: {0}", class1.strstaticreadonly );
  18. Console. Readline ();
  19. }
  20. }
  21. }

EXAMPLE After modification:

 
 
  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. }  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.