Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a DirectoryInfo object be safely use as a key in a Dictionary?

Tags:

c#

.net

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?

like image 453
d0001 Avatar asked Dec 19 '22 13:12

d0001


1 Answers

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.

like image 111
Reed Copsey Avatar answered May 19 '23 00:05

Reed Copsey