I'm new to Code Contract, and the document says all members that are mentioned in preconditions must be at least as accessible as the method itself, a private field cannot be mentioned in a precondition for a public method, therefore the code below doesn't compile:
using System;
using System.Diagnostics.Contracts;
public class UseFulLibrary{
private static Item item = null;
public static void Foo(Item newItem) {
Contract.Requires(newItem != item); // doesn't compile
}
}
public class Item { }
But it is OK to access private member in a public method if we have:
public class UseFulLibrary{
private static Item item = null;
public static void Foo(Item newItem) {
if (newItem != item) {
...
}
}
}
Clients can certainly call UseFulLibrary.Foo
method, even though the client cannot access the private static Item
field explicitly on their end, so why preconditions requires this unnecessary condition?