CodeContract considers the assigned readonly field to be null

I have this code:

public class CodeContractSample { private readonly List<object> _items = new List<object>(); public IEnumerable<object> Query() { Contract.Ensures(Contract.Result<IEnumerable<object>>() != null); //if (_items == null) throw new Exception(); return _items; } } 

CodeContracts gives the following warning:

CodeContracts: provides unproven: Contract.Result> ()! = Null

If I uncomment the middle line, it stops complaining. But why is he starting to complain? _items should never be null ..?

+4
source share
4 answers

Contracts are not 100%, and there are still gaps in understanding.

You are right: there is no reason for unproven results. For more information about this issue, see http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/f82aa25c-e858-4809-bc21-0a08de260bf1 .

Now you can solve this problem using:

 Contract.Assume(_items != null); 

You can also achieve this with contract invariants:

 [ContractInvariantMethod] void Invariants() { Contract.Invariant(_items != null); } 
+5
source

Why do you think the elements will never be empty? You may have another method in this class that sets it to null ...

0
source

Actually, I can imagine this:

 CodeContractSample s = new CodeContractSample(); s.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(s, null); var q = s.Query(); 

What do you think?

0
source

The Contract.Ensures line promises that the method will never return null. But there is nothing in the code to prevent this until you uncomment the line.

-1
source

Source: https://habr.com/ru/post/1337784/


All Articles