I am using Dictionary using objects like DirectoryInfo and FileInfo as keys. Is it safe to use them that way? How can I make sure an object type can be safely used this way?
In general, the only way to know exactly how this will behave is to check the reference source. You can check the documentation to see whether IEquatable<T>
is implemented (in which case you'll get "expected" behavior), as well.
If the type in question doesn't override Equals
and GetHashCode
, then the default hashing and equality for any object will be used. This means you can use it as a key, but only if your lookups are being done with the same instance of the type, since the equality is reference equality by default for System.Object
.
In this case, DirectoryInfo
and related classes do not override those methods, which means you'll get the default equality and hashing of object, which is likely not what you want. I would, instead, recommend using the FullName
property as a key, since it's a a string
and provides the proper equality semantics for use in a dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With