Hashtable indexer Definition:
// Summary: // Gets or sets the value associated with the specified key. // // Parameters: // Key: // The Key whose value to get or set. // // Returns: // The value associated with the specified key. If the specified key is not // Found, attempting to get it returns NULL, and attempting to set it creates // A new element using the specified key. // // Exceptions: // System. argumentnullexception: // Key is null. // // System. notsupportedexception: // The property is set and the system. Collections. hashtable is read-only.-or- // The property is set, key does not exist in the collection, and the system. Collections. hashtable // Has a fixed size. Public Virtual Object This [ Object Key] {Get; set ;}
It is explicitly written in returns that if the specified key cannot be found, the return value is null. So you can use the followingCodeFragment is desirable:
hashtable HS = New hashtable (); // Add some elements If (HS [ "key" ] = null ) { // The specified key does not found in hashtable }
Dictionary definition:
// Summary: // Gets or sets the value associated with the specified key. // // Parameters: // Key: // The Key of the value to get or set. // // Returns: // The value associated with the specified key. If the specified key is not // Found, a get operation throws a system. Collections. Generic. keynotfoundexception, // And a set operation creates a new element with the specified key. // // Exceptions: // System. argumentnullexception: // Key is null. // // System. Collections. Generic. keynotfoundexception: // The property is retrieved and key does not exist in the collection. Public Tvalue This [Tkey key] {Get; set ;}
Note: When the specified key does not exist, system. Collections. Generic. keynotfoundexception is thrown and a new element is automatically created with the current key.
Therefore, when using a dictionary, you cannot use hashtable to determine whether a key exists. Instead, you should use the following code snippet:
dictionary string , string dict = New dictionary string , string (); // Add some elements If (! Dict. containskey ( "key" )) { // The specified key does not found in dictionary }