Open yaakov-h opened 9 years ago
Can also add to this. We have something like this:
public static double GetScaledPixelIncrements(this IDiagramEntity diagramEntity)
{
Contract.Requires(diagramEntity != null); // Suggested By ReviewBot
var resolutionIncrementFactor = diagramEntity.ResolutionIncrement / (double)diagramEntity.Scale;
var scaleSizeInPixels = diagramEntity.ScaleUnitPixelSize;
return scaleSizeInPixels * resolutionIncrementFactor;
}
Getting a "reference use unreached" on the scaleSizeInPixels
variable as it's only used once in the return statement. The variables are introduced for readability and used once in the return statement, which I think is a fair use case.
I encountered another similar case today with C# 6's enhancement to properties. This code will trigger an "invariant unreachable":
using System.Diagnostics.Contracts;
namespace ContractCSharp6Properties
{
[ContractClass(typeof(FooContract))]
public interface IFoo
{
object Bar { get; }
}
[ContractClassFor(typeof(IFoo))]
abstract class FooContract : IFoo
{
public object Bar
{
get
{
Contract.Ensures(Contract.Result<object>() != null);
return default(object);
}
}
}
public class Foo : IFoo
{
public Foo(object bar)
{
Contract.Requires(bar != null);
Bar = bar;
}
public object Bar { get; }
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Bar != null);
}
}
}
Interestingly, if I strip out the interface, like so:
using System.Diagnostics.Contracts;
namespace ContractCSharp6Properties
{
public class Foo
{
public Foo(object bar)
{
Contract.Requires(bar != null);
Bar = bar;
}
public object Bar { get; }
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Bar != null);
}
}
}
I then get the following warning:
C:\Temp\ContractCSharp6Properties\ContractCSharp6Properties\Class1.cs(7,3): warning : CodeContracts: Invoking constructor 'ContractCSharp6Properties.Foo.#ctor(System.Object)' will always lead to a violation of an (inferred) object invariant
C:\Temp\ContractCSharp6Properties\ContractCSharp6Properties\Class1.cs(12,3): warning : CodeContracts: invariant is false: Bar != null
C:\Temp\ContractCSharp6Properties\ContractCSharp6Properties\Class1.cs(19,4): warning : + location related to previous warning
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ContractCSharp6Properties.dll(1,1): message : CodeContracts: Checked 5 assertions: 3 correct 1 unknown 1 false
Invoking constructor 'ContractCSharp6Properties.Foo.#ctor(System.Object)' will always lead to a violation of an (inferred) object invariant
This is false, and goes away if the interface is added and implemented.
Repro case:
VS2013 build output with
-show unreached
VS2015 build output with
-show unreached