Why can't you use null as a key for a Dictionary?

后端 未结 11 1906
长情又很酷
长情又很酷 2020-12-24 00:33

Apparently, you cannot use a null for a key, even if your key is a nullable type.

This code:

var nullableBoolLabels = new System.Collect         


        
11条回答
  •  一个人的身影
    2020-12-24 00:46

    I've just been reading up on this; and as Eric replied, I now believe this is incorrect, not all strings are automatically Interned, and I needed to override the equality operation.


    This bit me when I converted a dictionary from using a string as a key to an array of bytes.

    I was in the vanilla C mindset of a string simply being an array of characters, so it took me a while to figure out why a string built by concatenation worked as a key for lookups while a byte array built in a loop did not.

    It's because internally .net assigns all strings that contain the same value to the same reference. (it's called 'Interning')

    so, after running:

    {
    string str1 = "AB";
    string str2 = "A";
    str1 += "C";
    str2 += "BC";
    }
    

    str1 and str2 actually point to the exact same place in memory! which makes them the same onject; which allows a dictionary to find an item added with str1 as a key by using str2.

    while if you:

    {
    char[3] char1;
    char[3] char2;
    char1[0] = 'A';
    char1[1] = 'B';
    char1[2] = 'C';
    char2[0] = 'A';
    char2[1] = 'B';
    char2[2] = 'C';
    }
    

    char1 and char2 are distinct references; if you use char1 to add an item to a dictionary, you cannot use char2 to look it up.

提交回复
热议问题