Basically I want to know if using a code contract to determine if a key exists in a ConcurrentDictionary is an acceptable use of a code contract. It doesn't feel right to me because it's more than parameter check as it depends on the state of the dictionary at runtime.
public class MyClass
{
private ConcurrentDictionary<string, object> someItems =
new ConcurrentDictionary<string, object>();
public object GetItem(string itemName)
{
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(itemName));
// ?? Is this a correct alternative to checking for null???
Contract.Requires<KeyNotFoundException>(someItems.ContainsKey(itemName));
return someItems[itemName];
}
}
But if it is okay, it's a cleaner method that has 2 Contract.Requires and one return, over the traditional way below.
public class MyClass
{
private ConcurrentDictionary<string, object> someItems =
new ConcurrentDictionary<string, object>();
public object GetItem(string itemName)
{
Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(itemName));
// Traditional null check
var item = someItems[itemName];
if (item == null)
{
throw new KeyNotFoundException("Item " + itemName + " not found.");
}
return item;
}
}