Static readonly and const constant constants: When will it be used?
When dealing with constant values in C#, developers often face the problem of selecting fields and . This article discusses the appropriate scenario of the public constant value in the class to declare the public constant value in the class.
static readonly
const
to improve visibility. This ensures that external calories can access these values without affecting packaging.
static readonly
Variables are also immutable, but they are not specific to public members. They can be used in the internal, protected and private constant in the class. However, due to its inherent restrictions, it is not recommended to use static readonly
for public value.
Performance impact
The value can be directly embedded in the call site, which can improve performance in some cases. However, if the constant value is dynamically obtained (for example, from the configuration source), the optimization effect is not obvious. In addition, modifying the value requires re -constructing all client applications that reference it.
const
Attributes const
As an alternative to the field, the author recommends that consider using public static attributes with only Getter. These attributes can use private fields as backing, thereby providing greater flexibility and packaging. Conclusion
const
For the common amount of public, the choice of const
field and
Field recommendation is used for public visibility, and is more suitable for internal, protected or private value for never changing. If the performance is very important, you can consider the use of , but you should carefully weigh the shortcomings and potential benefits of unsatisfactory and reorganize the dependencies.
The above is the detailed content of Static Readonly vs. Const in C#: When Should I Use Which for Public Constants?. For more information, please follow other related articles on the PHP Chinese website!