I'm trying to work out how .NET Code Contracts interact with the lock
keyword, using the following example:
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();
}
}
}
When I run the Code Contract static analysis tool, it prints a a warning: Ensures unproven: this.o1 != null
If I do any of:
- change the
o2
in thelock
too1
, - change the
o1
inside thelock
block too2
, - adding a second line inside the
lock
block assigning anew
object
too2
- change
lock (this.o2)
toif (this.o2 != null)
, - remove the
lock
statement entirely.
the warning disappears.
However, changing the line inside the lock
block to var temp = new object();
(thus removing all references to o1
from the method) still causes the warning:
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();
}
}
So there are two questions:
- Why is this warning occurring?
- What can be done to prevent it (bearing in mind this is a toy example and there's actually stuff happening inside the
lock
in the real code)?