I am trying to integrate Code Contracts into some existing code and so far so good for the most part. The problem I am facing though is that I have set up contracts on an interface and one implementation delegates the implementation to a Func<> that is passed into the constructor of the class similar to the following:
[ContractClass(typeof(IFooContract))]
public interface IFoo
{
object Bar();
}
[ContractClassFor(typeof(IFoo))]
public abstract class IFooContract : IFoo
{
object IFoo.Bar()
{
Contract.Ensures(Contract.Result<object>() != null);
throw new NotImplementedException();
}
}
public class DelegatedFoo : IFoo
{
public DelegatedFoo(Func<object> barImplementation)
{
Contract.Requires(barImplementation != null);
_barImplementation = barImplementation;
}
private readonly Func<object> _barImplementation;
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(_barImplementation != null);
}
public object Bar()
{
//"ensures unproven: Contract.Result<object>() != null" here.
return _barImplementation();
}
}
The static analyser reports the error "ensures unproven: Contract.Result() != null". Can I define contracts on Func<> (and by extension on Action<>)?
Is this the best solution?
public class DelegatedFoo : IFoo
{
public DelegatedFoo(Func<object> barImplementation)
{
Contract.Requires(barImplementation != null);
_barImplementation = barImplementation;
}
private readonly Func<object> _barImplementation;
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(_barImplementation != null);
}
public object Bar()
{
var result = _barImplementation();
Contract.Assume(result != null);
return result;
}
}