Code Contracts: Why are some invariants not considered outside the class?

天大地大妈咪最大 提交于 2019-12-03 11:14:05

After checking the code contracts forum, I found this similar question with the following answer from one of the developers:

I think the behavior you are experiencing is caused by some inter-method inference that is going on. The static checker first analyzes the constructors, then the properties and then the methods. When analyzing the constructor of Sample, it does not know that msgContainer.Something != null so it issues the warning. A way to solve it, is either by adding an assumption msgContainer.Something != null in the constuctor, or better to add the postcondition != null to Something.

So in other words, your options are:

  1. Make the Settings.Path property explicit instead of automatic, and specify the invariant on the backing field instead. In order to satisfy your invariant, you will need to add a precondition to the property's set accessor: Contract.Requires(value != null).

    You can optionally add a postcondition to the get accessor with Contract.Ensures(Contract.Result<string>() != null), but the static checker will not complain either way.

  2. Add Contract.Assume(settings.Path != null) to the constructor of the Program class.

Invariants don't work on private members, you cannot actually have the reason why it is this way, hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!