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 ..?
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); }
Why do you think the elements will never be empty? You may have another method in this class that sets it to null ...
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?
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.
Source: https://habr.com/ru/post/1337784/More articles:Difference between window close event and click button event in HTML? - javascriptTDD duplication of test data - unit-testingBuilding exceptions in C # - c #How can I make a back link on PHP pages? - phpExchange 2007 Server - Error ExchangeServiceBinding :: UpdateItem - exchange-serverHow to create and copy a class library for output without reference to it in Visual Studio? - visual-studioBitmap.NET CF quality is poor - c #CE DrawLine Smoothing - c #Java finds the beginning of a file name and extension - javaHow to create a Dropdown Choice filter field in Django using ajax? - djangoAll Articles