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

后端 未结 11 1901
长情又很酷
长情又很酷 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:52

    It would tell you the same thing if you had a Dictionary, SomeType being a reference type, and you tried to pass null as the key, it is not something affecting only nullable type like bool?. You can use any type as the key, nullable or not.

    It all comes down to the fact that you can't really compare nulls. I assume the logic behind not being able to put null in the key, a property that is designed to be compared with other objects is that it makes it incoherent to compare null references.

    If you want a reason from the specs, it boils down to a "A key cannot be a null reference " on MSDN.

    If you want an exemple of a possible workaround, you can try something similar to Need an IDictionary implementation that will allow a null key

提交回复
热议问题