You can avoid using null and create a special Singleton value class that does the same. For example:
public sealed class Nothing { public static readonly Nothing Value = new Nothing(); private Nothing() {} } Dictionary<object, string> dict = new Dictionary<object, string>(); dict.add(Nothing.Value, "Nothing"); dict.add(1, "One");
This approach will not work if you intend to make your collection more strongly typed - say, for example, you want the key to be a string. Since the string is sealed, you cannot inherit it to create a replacement for the "special value" for null. Your alternatives are getting a little harder. You could:
- Create a special constant value to represent the empty / null case. Kind of khaki and definitely a path to confusion. This can be a viable approach if the dictionary is completely closed for any implementation class, and you can write some methods of the Encode / Decode utility so as not to spread the knowledge of how you translate keys around the place.
- Create your own implementation of IDictionary that internally delegates an instance of Dictionary <>, except in the case of null. This violates the documented expectations for the IDictionary <> interface, which says that empty keys should throw an exception. But you can get away from it if this is the only way to solve your real problem. This only works if you own and create an instance of the dictionary.
- Find a way to solve your problem without storing the "zero" key in the dictionary. For example, consider not filling out the null key in the dictionary and have some special case logic to solve this problem. The keys must be hashed and comparable to working with the underlying implementation, so zero is prohibited in normal mode.
As an aside, is your key dictionary really needed for the object key? This can lead to minor errors due to the use of reference equality, when you can assume that Equals () is evaluated as the basis for comparison.
LBushkin Dec 16 '09 at 18:57 2009-12-16 18:57
source share