ado| difference
The difference between const and readonly is always not clear, so check the data.
The concept of the
const is a variable that contains a value that cannot be modified. A
constant expression is an expression that can be fully evaluated at compile time. Therefore, you cannot initialize constants by extracting values from a variable.
If const int a = b+1; b is a variable, obviously can not be compiled to calculate the results, so constants can not be initialized with variables. The
readonly allows you to set a field to a constant, but you can perform some operations to determine its initial value.
because readonly is performed at calculation time, of course it can be initialized with certain variables.
readonly is an instance member, so different instances can have different constant values, which makes readonly more flexible. The
readonly keyword differs from the const keyword.
1. The const field can only be initialized in the declaration of that field. The
readonly field can be initialized in a declaration or a constructor. Therefore, depending on the constructor used, the ReadOnly field may have different values. The
2. const field is a compile-time constant, while the readonly field can be used to run the constant number.
3. const is static by default, and readonly if set to static, the declaration must be displayed.
4. const for constants of reference types, the possible values can only be string and null .
readonly can be any type
* One of the issues that you need to be aware of is:
For a readonly Reference type, it is limited to the assignment (write) operation. The reading and writing of its members is still unrestricted.
public static readonly Class1 i = new Class1 ();
...
My. Someproperty = ten; //Normal
My = new Class1 (); Error, the object is read-only
However, if the Class1 in the example above is not a Class but a struct, then the following two statements will be faulted.
static readonly:
static in Java is performed once when a class is loaded.
I didn't find out how to do it in C #. It is strange that almost every Java book will say Static, C # often only say how to use, but it should be initialized before the main function call, so the static readonly is also run-time, you can use variables to pay the value, such as:
private static readonly String path = System.Windows.Forms.Application.StartupPath + "AAA";