“const correctness” in C#

前端 未结 7 1470
执念已碎
执念已碎 2020-11-28 05:29

The point of const-correctness is to be able to provide a view of an instance that can\'t be altered or deleted by the user. The compiler supports this by pointing out when

7条回答
  •  隐瞒了意图╮
    2020-11-28 05:31

    • The const keyword can be used for compile time constants such as primitive types and strings
    • The readonly keyword can be used for run-time constants such as reference types

    The problem with readonly is that it only allows the reference (pointer) to be constant. The thing referenced (pointed to) can still be modified. This is the tricky part but there is no way around it. To implement constant objects means making them not expose any mutable methods or properties but this is awkward.

    See also Effective C#: 50 Specific Ways to Improve Your C# (Item 2 - Prefer readonly to const.)

提交回复
热议问题