C# in the comparison of static readonly
: When will it be used? const
When defining the constant value in C# class,
field or variables are usually used. However, the two have their own meaning and use cases. static readonly
const
Public static reading only fields (
public static readonly
Fields are usually used to maintain unchanged in the entire application and access to it from any location. They are initialized during the loading period and cannot be modified afterwards.
) public static readonly
In contrast, Variables are usually used in the internal implementation of details or unintentional values. The compiler optimizes it and is directly embedded in the call site, which may improve performance. const
Suggestions: For public constant use of static reading,
const
For the constant value that needs to be disclosed and does not change over time, it is usually recommended to use the
The use of attributes
Consider the use of the attributes of only static readonly
accessors, not directly accessing fields. This provides additional control of values, allowing potential conversion or verification before returning values.
The limitations of
There are some limitations: get
They must initialize with constant expressions.
const
Change the value to re -build all client assemblies.
const
const
The above is the detailed content of `Static readonly` vs. `const` in C#: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!