Why doesn't HashTable.Contains() just simply return false if it is passed a null?
I understand why passing a null to HashTable.Contains() doesn't work, but I don't understand what the point of it throwing an ArgumentNullException
is - instead of just simply returning false
? What is the benefit of throwing the exception (other than to make me do null checks befor开发者_高级运维e calling .Contains()
)?
Caused By [System.ArgumentNullException]
Key cannot be null. Parameter name: key at System.Collections.Hashtable.ContainsKey(Object key) at System.Collections.Hashtable.Contains(Object key)
false
means that the hash table doesn't contain the key supplied.
There needs to be another way of indicating that you've supplied an invalid key.
You could always wrap HashTable.Contains
in another method that does the checking for null (or traps the exception) and returns false
in this case.
This is because it doesn't make sense to pass null
, since null
can not be a key. So the library throws an exception instead to let you know that there is something wrong elsewhere in your code. If it hadn't thrown an exception, it would be more difficult to track down where something went wrong.
You could do something along the lines of:
return x == null ? false : HashTable.Contains(x);
...if you wanted.
One reason you mentioned by yourself: "make me do null checks". Second is that you can't say is null
contained by HashTable
, this has no meaning. Returning false would be a hack.
Semantically speaking, every set contains null. So it would be more correct to return true rather than false. Of course, this isn't very useful at all. Throwing the exception is the appropriate way to handle it.
精彩评论