Problem # 1 is the result of Settings.Default.MyDirectoryPath , which is code created by Visual Studio without any property contracts. This problem is not limited to null strings. Many APIs now have contracts that require TimeSpan be non-negative, but using a parameter directly associated with the API, a code contract warning will be generated.
The way to solve this problem is to wrap the parameter in a method that has a contract. For instance:.
String GetMyDirectoryPath() { Contract.Ensures(Contract.Result<String>() != null); var myDirectoryPath = Settings.Default.MyDirectoryPath; Contract.Assume(myDirectoryPath != null); return myDirectoryPath; }
Note that Contract.Assume really does validate your parameter (which cannot be verified by code contracts, as it is controlled by an external configuration file). If there was a TimeSpan , which is expected to be non-negative, you can use Contract.Assume to perform a check leading to a ContractException or other method, using your own exception instead.
Adding this extra layer is somewhat tedious, but since the parameter is defined outside the application, it must be checked at runtime at some point, just like you need to check the user's interactive input.
Problem number 2 is probably because DirectoryInfo does not have any contracts. The easiest way to use Contract.Assume . This will make an expression about what you think DirectoryInfo expected behavior is, but the runtime check will still be in place to make sure your belief is correct (assuming you keep the checks in your code).
var path = MyDirectory.FullName; Contract.Assume(!string.IsNullOrEmpty(path)); var catalog = new DirectoryCatalog(path);
source share