I'm having an argument with the CodeContracts static analysis tool.
My code:
(ASCII version)
The tool tells me that instance.bar
may be a null reference. I believe the opposite.
Who is right? How can I prove it wrong?
Update: It seems the problem is that invariants are not supported for static fields.
2nd Update: The method outlined below is currently the recommended solution.
A possible workaround is to create a property for instance
that Ensure
s the invariants that you want to hold. (Of course, you need to Assume
them for the Ensure
to be proven.) Once you have done this, you can just use the property and all the invariants should be proven correctly.
Here's your example using this method:
class Foo
{
private static readonly Foo instance = new Foo();
private readonly string bar;
public static Foo Instance
// workaround for not being able to put invariants on static fields
{
get
{
Contract.Ensures(Contract.Result<Foo>() != null);
Contract.Ensures(Contract.Result<Foo>().bar != null);
Contract.Assume(instance.bar != null);
return instance;
}
}
public Foo()
{
Contract.Ensures(bar != null);
bar = "Hello world!";
}
public static int BarLength()
{
Contract.Assert(Instance != null);
Contract.Assert(Instance.bar != null);
// both of these are proven ok
return Instance.bar.Length;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With