Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to specify that some class's instances should not be used as dictionary keys?
    text
    copied!<p>I am interested in your opinion regarding an issue that came up while implementing a small library for writing integration/system tests in C#. The library is composed of 2 parts: a test Authoring API and a test Runtime API. The test writer uses the authoring API to build test plan prototypes. The runtime can take the a prototype and create a runtime representation of the prototype and execute it. </p> <p>To be able to test a class named RuntimeTestPlanBuilder I had to override the Equals method on the entire runtime object model classes. This led to a situation where I should override the GetHashCode method too. Implementing GetHashCode for some of the runtime object model classes was easy. Since some classes on the runtime model are containers implementing GetHashCode for them was tough and even impossible (since the runtime can add items to a container the hash code cannot be computed in O(1), for example). </p> <p>As a result I found myself wondering how to prevent from users of the containers to put them on a dictionary as keys. The solution I chose is to override the GetHashCode method and throw an exception. I am not satisfied with this solution since it will only fail on runtime. Plus, I kind of wonder why the .Net Framework designers chose to put the GetHashCode method on the Object class. I think that this decision led to my situation since I cannot mark my containers as not legitimate dictionary keys in a fine way.</p> <p>A better decision (for the .Net Framework designers) might have been to define an interface named IHashable with 2 methods: Equals and GetHashCode and enforce the interface with a constraint over the generic dictionary Item type. This way we can enforce in compile time that keys implement the Equals and GetHashCode. Also, it is easy to understand that classes that do not implement this interface are not supposed to be used as dictionary keys.</p> <p>My question is: Can you propose a better solution (one that do not throw exceptions from GetHashCode) to speciy that some class's instances should not be used as dictionary keys?</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload