Looking at the code sample below, Microsoft Code Contracts warns:
CodeContracts: Missing precondition in an extremely visible method. Consider adding Contract.Requires(science == null); for parameter validation
Am I missing something here? Why would CC suggest that I require the parameter to be null, which is the exact opposite of what should be done here?
I'm using VS2015, .NET 4.6.
using System;
using System.Diagnostics.Contracts;
public sealed class Weird
{
public Weird(object science)
{
if (null == science)
{
throw new ArgumentNullException();
}
Contract.EndContractBlock();
this.Science = science;
}
private object Science { get; }
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(null != this.Science);
}
}
This isn't a much better answer than your workaround, but I got it to "work" by simply changing:
private object Science { get; }
to:
private object Science { get; set; }
Basically the same as your workaround but without providing your own backing field. I guess Code Contracts doesn't quite understand the new syntax.