Note that there are some explanatory texts on larger screens.

plurals
  1. POCode Contracts warn of "ensures unproven" when locks are involved
    primarykey
    data
    text
    <p>I'm trying to work out how .NET Code Contracts interact with the <code>lock</code> keyword, using the following example:</p> <pre class="lang-cs prettyprint-override"><code>public class TestClass { private object o1 = new object(); private object o2 = new object(); private void Test() { Contract.Requires(this.o1 != null); Contract.Requires(this.o2 != null); Contract.Ensures(this.o1 != null); lock (this.o2) { this.o1 = new object(); } } } </code></pre> <p>When I run the Code Contract static analysis tool, it prints a a warning: <code>Ensures unproven: this.o1 != null</code></p> <p>If I do any of:</p> <ul> <li>change the <code>o2</code> in the <code>lock</code> to <code>o1</code>,</li> <li>change the <code>o1</code> inside the <code>lock</code> block to <code>o2</code>,</li> <li>adding a second line inside the <code>lock</code> block assigning a <code>new</code> <code>object</code> to <code>o2</code></li> <li>change <code>lock (this.o2)</code> to <code>if (this.o2 != null)</code>,</li> <li>remove the <code>lock</code> statement entirely.</li> </ul> <p>the warning disappears.</p> <p>However, changing the line inside the <code>lock</code> block to <code>var temp = new object();</code> (thus removing all references to <code>o1</code> from the method) still causes the warning:</p> <pre class="lang-cs prettyprint-override"><code>private void Test() { Contract.Requires(this.o1 != null); Contract.Requires(this.o2 != null); Contract.Ensures(this.o1 != null); lock (this.o2) { var temp = new object(); } } </code></pre> <hr> <p>So there are two questions:</p> <ol> <li>Why is this warning occurring?</li> <li>What can be done to prevent it (bearing in mind this is a toy example and there's actually stuff happening inside the <code>lock</code> in the real code)?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload