One class I am writing implements IDictionary<string, object>. In my CopyTo implementation, I would like to use code contracts: stuff like Contract.Requires<ArgumentNullException>(array != null).
But, I get this warning (with some namespaces removed for readability):
Method ‘LuaDictionary.CopyTo(KeyValuePair<String,Object>[],Int32)‘ implements interface method ‘ICollection<KeyValuePair<String,Object>>.CopyTo(KeyValuePair<String,Object>[],Int32)‘, thus cannot add Requires.
I see that there are some related questions, but they all seem to have to do with interfaces that are under the user’s control. Obviously, IDictionary<T, U> is not under my control, so I can’t annotate it with ContractClassFor or anything like that.
So am I just unable to use code contracts here? If so… major bummer…
It is a bummer, but is understandable because client code that uses instances of your class as
IDictionary<string, object>should not have to meet preconditions that are not expected ofIDictionary<string, object>.You can read the answer provided to this SO question, which links to and quotes the Code Contracts User Manual, and you can look at this article, which explains the situation this way, and goes on to provide a simple example: