Say I have the following
public T Example(Func<T> f)
{
Contract.Requires(f != null);
Contract.Requires(f() != null); // no surprise, this is an error
...
}
Is there any way to specify that my Func<T> parameters must obey some contracts?
In general, that seems like a problematic requirement since invoking
fmay introduce side effects so specifying a contract could affect what the method does.As the implementer of the Code Contracts library one could introduce wrapper code that checks to see if the value of
fobeys the contract when it is invoked in the context of your method (to avoid introducing a spurious method call). This is problematic for a couple of reasons:f, so the caller could violate the contract and not get busted.fonly after doing some other work which might be invalid given that the call tofdidn’t satisfy the specification.If
fhad no side effects then these wouldn’t be problems, but in the presence of side effects dealing with 1 by always callingfwouldn’t work and callingfbefore doing any work to deal with 2 also wouldn’t fly.So, in conclusion I don’t think that this is possible (in the context of native code contracts) and with good reason.